4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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
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
){
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
);
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
63 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
64 return sqlite3AffinityType(pExpr
->u
.zToken
, 0);
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
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
) );
88 if( op
!=TK_REGISTER
|| (op
= pExpr
->op2
)==TK_REGISTER
) break;
90 return pExpr
->affExpr
;
94 ** Make a guess at all the possible datatypes of the result that could
95 ** be returned by an expression. Return a bitmask indicating the answer:
101 ** If the expression must return NULL, then 0x00 is returned.
103 int sqlite3ExprDataType(const Expr
*pExpr
){
109 pExpr
= pExpr
->pLeft
;
126 case TK_AGG_FUNCTION
:
134 case TK_SELECT_COLUMN
:
136 int aff
= sqlite3ExprAffinity(pExpr
);
137 if( aff
>=SQLITE_AFF_NUMERIC
) return 0x05;
138 if( aff
==SQLITE_AFF_TEXT
) return 0x06;
144 ExprList
*pList
= pExpr
->x
.pList
;
145 assert( ExprUseXList(pExpr
) && pList
!=0 );
146 assert( pList
->nExpr
> 0);
147 for(ii
=1; ii
<pList
->nExpr
; ii
+=2){
148 res
|= sqlite3ExprDataType(pList
->a
[ii
].pExpr
);
150 if( pList
->nExpr
% 2 ){
151 res
|= sqlite3ExprDataType(pList
->a
[pList
->nExpr
-1].pExpr
);
158 } /* End of switch(op) */
159 } /* End of while(pExpr) */
164 ** Set the collating sequence for expression pExpr to be the collating
165 ** sequence named by pToken. Return a pointer to a new Expr node that
166 ** implements the COLLATE operator.
168 ** If a memory allocation error occurs, that fact is recorded in pParse->db
169 ** and the pExpr parameter is returned unchanged.
171 Expr
*sqlite3ExprAddCollateToken(
172 const Parse
*pParse
, /* Parsing context */
173 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
174 const Token
*pCollName
, /* Name of collating sequence */
175 int dequote
/* True to dequote pCollName */
177 if( pCollName
->n
>0 ){
178 Expr
*pNew
= sqlite3ExprAlloc(pParse
->db
, TK_COLLATE
, pCollName
, dequote
);
181 pNew
->flags
|= EP_Collate
|EP_Skip
;
187 Expr
*sqlite3ExprAddCollateString(
188 const Parse
*pParse
, /* Parsing context */
189 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
190 const char *zC
/* The collating sequence name */
194 sqlite3TokenInit(&s
, (char*)zC
);
195 return sqlite3ExprAddCollateToken(pParse
, pExpr
, &s
, 0);
199 ** Skip over any TK_COLLATE operators.
201 Expr
*sqlite3ExprSkipCollate(Expr
*pExpr
){
202 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
) ){
203 assert( pExpr
->op
==TK_COLLATE
);
204 pExpr
= pExpr
->pLeft
;
210 ** Skip over any TK_COLLATE operators and/or any unlikely()
211 ** or likelihood() or likely() functions at the root of an
214 Expr
*sqlite3ExprSkipCollateAndLikely(Expr
*pExpr
){
215 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
|EP_Unlikely
) ){
216 if( ExprHasProperty(pExpr
, EP_Unlikely
) ){
217 assert( ExprUseXList(pExpr
) );
218 assert( pExpr
->x
.pList
->nExpr
>0 );
219 assert( pExpr
->op
==TK_FUNCTION
);
220 pExpr
= pExpr
->x
.pList
->a
[0].pExpr
;
222 assert( pExpr
->op
==TK_COLLATE
);
223 pExpr
= pExpr
->pLeft
;
230 ** Return the collation sequence for the expression pExpr. If
231 ** there is no defined collating sequence, return NULL.
233 ** See also: sqlite3ExprNNCollSeq()
235 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
236 ** default collation if pExpr has no defined collation.
238 ** The collating sequence might be determined by a COLLATE operator
239 ** or by the presence of a column with a defined collating sequence.
240 ** COLLATE operators take first precedence. Left operands take
241 ** precedence over right operands.
243 CollSeq
*sqlite3ExprCollSeq(Parse
*pParse
, const Expr
*pExpr
){
244 sqlite3
*db
= pParse
->db
;
246 const Expr
*p
= pExpr
;
249 if( op
==TK_REGISTER
) op
= p
->op2
;
250 if( (op
==TK_AGG_COLUMN
&& p
->y
.pTab
!=0)
251 || op
==TK_COLUMN
|| op
==TK_TRIGGER
254 assert( ExprUseYTab(p
) );
255 assert( p
->y
.pTab
!=0 );
256 if( (j
= p
->iColumn
)>=0 ){
257 const char *zColl
= sqlite3ColumnColl(&p
->y
.pTab
->aCol
[j
]);
258 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
262 if( op
==TK_CAST
|| op
==TK_UPLUS
){
267 assert( ExprUseXList(p
) );
268 p
= p
->x
.pList
->a
[0].pExpr
;
271 if( op
==TK_COLLATE
){
272 assert( !ExprHasProperty(p
, EP_IntValue
) );
273 pColl
= sqlite3GetCollSeq(pParse
, ENC(db
), 0, p
->u
.zToken
);
276 if( p
->flags
& EP_Collate
){
277 if( p
->pLeft
&& (p
->pLeft
->flags
& EP_Collate
)!=0 ){
280 Expr
*pNext
= p
->pRight
;
281 /* The Expr.x union is never used at the same time as Expr.pRight */
282 assert( !ExprUseXList(p
) || p
->x
.pList
==0 || p
->pRight
==0 );
283 if( ExprUseXList(p
) && p
->x
.pList
!=0 && !db
->mallocFailed
){
285 for(i
=0; i
<p
->x
.pList
->nExpr
; i
++){
286 if( ExprHasProperty(p
->x
.pList
->a
[i
].pExpr
, EP_Collate
) ){
287 pNext
= p
->x
.pList
->a
[i
].pExpr
;
298 if( sqlite3CheckCollSeq(pParse
, pColl
) ){
305 ** Return the collation sequence for the expression pExpr. If
306 ** there is no defined collating sequence, return a pointer to the
307 ** default collation sequence.
309 ** See also: sqlite3ExprCollSeq()
311 ** The sqlite3ExprCollSeq() routine works the same except that it
312 ** returns NULL if there is no defined collation.
314 CollSeq
*sqlite3ExprNNCollSeq(Parse
*pParse
, const Expr
*pExpr
){
315 CollSeq
*p
= sqlite3ExprCollSeq(pParse
, pExpr
);
316 if( p
==0 ) p
= pParse
->db
->pDfltColl
;
322 ** Return TRUE if the two expressions have equivalent collating sequences.
324 int sqlite3ExprCollSeqMatch(Parse
*pParse
, const Expr
*pE1
, const Expr
*pE2
){
325 CollSeq
*pColl1
= sqlite3ExprNNCollSeq(pParse
, pE1
);
326 CollSeq
*pColl2
= sqlite3ExprNNCollSeq(pParse
, pE2
);
327 return sqlite3StrICmp(pColl1
->zName
, pColl2
->zName
)==0;
331 ** pExpr is an operand of a comparison operator. aff2 is the
332 ** type affinity of the other operand. This routine returns the
333 ** type affinity that should be used for the comparison operator.
335 char sqlite3CompareAffinity(const Expr
*pExpr
, char aff2
){
336 char aff1
= sqlite3ExprAffinity(pExpr
);
337 if( aff1
>SQLITE_AFF_NONE
&& aff2
>SQLITE_AFF_NONE
){
338 /* Both sides of the comparison are columns. If one has numeric
339 ** affinity, use that. Otherwise use no affinity.
341 if( sqlite3IsNumericAffinity(aff1
) || sqlite3IsNumericAffinity(aff2
) ){
342 return SQLITE_AFF_NUMERIC
;
344 return SQLITE_AFF_BLOB
;
347 /* One side is a column, the other is not. Use the columns affinity. */
348 assert( aff1
<=SQLITE_AFF_NONE
|| aff2
<=SQLITE_AFF_NONE
);
349 return (aff1
<=SQLITE_AFF_NONE
? aff2
: aff1
) | SQLITE_AFF_NONE
;
354 ** pExpr is a comparison operator. Return the type affinity that should
355 ** be applied to both operands prior to doing the comparison.
357 static char comparisonAffinity(const Expr
*pExpr
){
359 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_IN
|| pExpr
->op
==TK_LT
||
360 pExpr
->op
==TK_GT
|| pExpr
->op
==TK_GE
|| pExpr
->op
==TK_LE
||
361 pExpr
->op
==TK_NE
|| pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
);
362 assert( pExpr
->pLeft
);
363 aff
= sqlite3ExprAffinity(pExpr
->pLeft
);
365 aff
= sqlite3CompareAffinity(pExpr
->pRight
, aff
);
366 }else if( ExprUseXSelect(pExpr
) ){
367 aff
= sqlite3CompareAffinity(pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
, aff
);
369 aff
= SQLITE_AFF_BLOB
;
375 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
376 ** idx_affinity is the affinity of an indexed column. Return true
377 ** if the index with affinity idx_affinity may be used to implement
378 ** the comparison in pExpr.
380 int sqlite3IndexAffinityOk(const Expr
*pExpr
, char idx_affinity
){
381 char aff
= comparisonAffinity(pExpr
);
382 if( aff
<SQLITE_AFF_TEXT
){
385 if( aff
==SQLITE_AFF_TEXT
){
386 return idx_affinity
==SQLITE_AFF_TEXT
;
388 return sqlite3IsNumericAffinity(idx_affinity
);
392 ** Return the P5 value that should be used for a binary comparison
393 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
395 static u8
binaryCompareP5(
396 const Expr
*pExpr1
, /* Left operand */
397 const Expr
*pExpr2
, /* Right operand */
398 int jumpIfNull
/* Extra flags added to P5 */
400 u8 aff
= (char)sqlite3ExprAffinity(pExpr2
);
401 aff
= (u8
)sqlite3CompareAffinity(pExpr1
, aff
) | (u8
)jumpIfNull
;
406 ** Return a pointer to the collation sequence that should be used by
407 ** a binary comparison operator comparing pLeft and pRight.
409 ** If the left hand expression has a collating sequence type, then it is
410 ** used. Otherwise the collation sequence for the right hand expression
411 ** is used, or the default (BINARY) if neither expression has a collating
414 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
415 ** it is not considered.
417 CollSeq
*sqlite3BinaryCompareCollSeq(
424 if( pLeft
->flags
& EP_Collate
){
425 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
426 }else if( pRight
&& (pRight
->flags
& EP_Collate
)!=0 ){
427 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
429 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
431 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
437 /* Expression p is a comparison operator. Return a collation sequence
438 ** appropriate for the comparison operator.
440 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
441 ** However, if the OP_Commuted flag is set, then the order of the operands
442 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
443 ** correct collating sequence is found.
445 CollSeq
*sqlite3ExprCompareCollSeq(Parse
*pParse
, const Expr
*p
){
446 if( ExprHasProperty(p
, EP_Commuted
) ){
447 return sqlite3BinaryCompareCollSeq(pParse
, p
->pRight
, p
->pLeft
);
449 return sqlite3BinaryCompareCollSeq(pParse
, p
->pLeft
, p
->pRight
);
454 ** Generate code for a comparison operator.
456 static int codeCompare(
457 Parse
*pParse
, /* The parsing (and code generating) context */
458 Expr
*pLeft
, /* The left operand */
459 Expr
*pRight
, /* The right operand */
460 int opcode
, /* The comparison opcode */
461 int in1
, int in2
, /* Register holding operands */
462 int dest
, /* Jump here if true. */
463 int jumpIfNull
, /* If true, jump if either operand is NULL */
464 int isCommuted
/* The comparison has been commuted */
470 if( pParse
->nErr
) return 0;
472 p4
= sqlite3BinaryCompareCollSeq(pParse
, pRight
, pLeft
);
474 p4
= sqlite3BinaryCompareCollSeq(pParse
, pLeft
, pRight
);
476 p5
= binaryCompareP5(pLeft
, pRight
, jumpIfNull
);
477 addr
= sqlite3VdbeAddOp4(pParse
->pVdbe
, opcode
, in2
, dest
, in1
,
478 (void*)p4
, P4_COLLSEQ
);
479 sqlite3VdbeChangeP5(pParse
->pVdbe
, (u8
)p5
);
484 ** Return true if expression pExpr is a vector, or false otherwise.
486 ** A vector is defined as any expression that results in two or more
487 ** columns of result. Every TK_VECTOR node is an vector because the
488 ** parser will not generate a TK_VECTOR with fewer than two entries.
489 ** But a TK_SELECT might be either a vector or a scalar. It is only
490 ** considered a vector if it has two or more result columns.
492 int sqlite3ExprIsVector(const Expr
*pExpr
){
493 return sqlite3ExprVectorSize(pExpr
)>1;
497 ** If the expression passed as the only argument is of type TK_VECTOR
498 ** return the number of expressions in the vector. Or, if the expression
499 ** is a sub-select, return the number of columns in the sub-select. For
500 ** any other type of expression, return 1.
502 int sqlite3ExprVectorSize(const Expr
*pExpr
){
504 if( op
==TK_REGISTER
) op
= pExpr
->op2
;
506 assert( ExprUseXList(pExpr
) );
507 return pExpr
->x
.pList
->nExpr
;
508 }else if( op
==TK_SELECT
){
509 assert( ExprUseXSelect(pExpr
) );
510 return pExpr
->x
.pSelect
->pEList
->nExpr
;
517 ** Return a pointer to a subexpression of pVector that is the i-th
518 ** column of the vector (numbered starting with 0). The caller must
519 ** ensure that i is within range.
521 ** If pVector is really a scalar (and "scalar" here includes subqueries
522 ** that return a single column!) then return pVector unmodified.
524 ** pVector retains ownership of the returned subexpression.
526 ** If the vector is a (SELECT ...) then the expression returned is
527 ** just the expression for the i-th term of the result set, and may
528 ** not be ready for evaluation because the table cursor has not yet
531 Expr
*sqlite3VectorFieldSubexpr(Expr
*pVector
, int i
){
532 assert( i
<sqlite3ExprVectorSize(pVector
) || pVector
->op
==TK_ERROR
);
533 if( sqlite3ExprIsVector(pVector
) ){
534 assert( pVector
->op2
==0 || pVector
->op
==TK_REGISTER
);
535 if( pVector
->op
==TK_SELECT
|| pVector
->op2
==TK_SELECT
){
536 assert( ExprUseXSelect(pVector
) );
537 return pVector
->x
.pSelect
->pEList
->a
[i
].pExpr
;
539 assert( ExprUseXList(pVector
) );
540 return pVector
->x
.pList
->a
[i
].pExpr
;
547 ** Compute and return a new Expr object which when passed to
548 ** sqlite3ExprCode() will generate all necessary code to compute
549 ** the iField-th column of the vector expression pVector.
551 ** It is ok for pVector to be a scalar (as long as iField==0).
552 ** In that case, this routine works like sqlite3ExprDup().
554 ** The caller owns the returned Expr object and is responsible for
555 ** ensuring that the returned value eventually gets freed.
557 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
558 ** then the returned object will reference pVector and so pVector must remain
559 ** valid for the life of the returned object. If pVector is a TK_VECTOR
560 ** or a scalar expression, then it can be deleted as soon as this routine
563 ** A trick to cause a TK_SELECT pVector to be deleted together with
564 ** the returned Expr object is to attach the pVector to the pRight field
565 ** of the returned TK_SELECT_COLUMN Expr object.
567 Expr
*sqlite3ExprForVectorField(
568 Parse
*pParse
, /* Parsing context */
569 Expr
*pVector
, /* The vector. List of expressions or a sub-SELECT */
570 int iField
, /* Which column of the vector to return */
571 int nField
/* Total number of columns in the vector */
574 if( pVector
->op
==TK_SELECT
){
575 assert( ExprUseXSelect(pVector
) );
576 /* The TK_SELECT_COLUMN Expr node:
578 ** pLeft: pVector containing TK_SELECT. Not deleted.
579 ** pRight: not used. But recursively deleted.
580 ** iColumn: Index of a column in pVector
581 ** iTable: 0 or the number of columns on the LHS of an assignment
582 ** pLeft->iTable: First in an array of register holding result, or 0
583 ** if the result is not yet computed.
585 ** sqlite3ExprDelete() specifically skips the recursive delete of
586 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
587 ** can be attached to pRight to cause this node to take ownership of
588 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
589 ** with the same pLeft pointer to the pVector, but only one of them
590 ** will own the pVector.
592 pRet
= sqlite3PExpr(pParse
, TK_SELECT_COLUMN
, 0, 0);
594 ExprSetProperty(pRet
, EP_FullSize
);
595 pRet
->iTable
= nField
;
596 pRet
->iColumn
= iField
;
597 pRet
->pLeft
= pVector
;
600 if( pVector
->op
==TK_VECTOR
){
602 assert( ExprUseXList(pVector
) );
603 ppVector
= &pVector
->x
.pList
->a
[iField
].pExpr
;
605 if( IN_RENAME_OBJECT
){
606 /* This must be a vector UPDATE inside a trigger */
611 pRet
= sqlite3ExprDup(pParse
->db
, pVector
, 0);
617 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
618 ** it. Return the register in which the result is stored (or, if the
619 ** sub-select returns more than one column, the first in an array
620 ** of registers in which the result is stored).
622 ** If pExpr is not a TK_SELECT expression, return 0.
624 static int exprCodeSubselect(Parse
*pParse
, Expr
*pExpr
){
626 #ifndef SQLITE_OMIT_SUBQUERY
627 if( pExpr
->op
==TK_SELECT
){
628 reg
= sqlite3CodeSubselect(pParse
, pExpr
);
635 ** Argument pVector points to a vector expression - either a TK_VECTOR
636 ** or TK_SELECT that returns more than one column. This function returns
637 ** the register number of a register that contains the value of
638 ** element iField of the vector.
640 ** If pVector is a TK_SELECT expression, then code for it must have
641 ** already been generated using the exprCodeSubselect() routine. In this
642 ** case parameter regSelect should be the first in an array of registers
643 ** containing the results of the sub-select.
645 ** If pVector is of type TK_VECTOR, then code for the requested field
646 ** is generated. In this case (*pRegFree) may be set to the number of
647 ** a temporary register to be freed by the caller before returning.
649 ** Before returning, output parameter (*ppExpr) is set to point to the
650 ** Expr object corresponding to element iElem of the vector.
652 static int exprVectorRegister(
653 Parse
*pParse
, /* Parse context */
654 Expr
*pVector
, /* Vector to extract element from */
655 int iField
, /* Field to extract from pVector */
656 int regSelect
, /* First in array of registers */
657 Expr
**ppExpr
, /* OUT: Expression element */
658 int *pRegFree
/* OUT: Temp register to free */
661 assert( op
==TK_VECTOR
|| op
==TK_REGISTER
|| op
==TK_SELECT
|| op
==TK_ERROR
);
662 if( op
==TK_REGISTER
){
663 *ppExpr
= sqlite3VectorFieldSubexpr(pVector
, iField
);
664 return pVector
->iTable
+iField
;
667 assert( ExprUseXSelect(pVector
) );
668 *ppExpr
= pVector
->x
.pSelect
->pEList
->a
[iField
].pExpr
;
669 return regSelect
+iField
;
672 assert( ExprUseXList(pVector
) );
673 *ppExpr
= pVector
->x
.pList
->a
[iField
].pExpr
;
674 return sqlite3ExprCodeTemp(pParse
, *ppExpr
, pRegFree
);
680 ** Expression pExpr is a comparison between two vector values. Compute
681 ** the result of the comparison (1, 0, or NULL) and write that
682 ** result into register dest.
684 ** The caller must satisfy the following preconditions:
686 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
687 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
688 ** otherwise: op==pExpr->op and p5==0
690 static void codeVectorCompare(
691 Parse
*pParse
, /* Code generator context */
692 Expr
*pExpr
, /* The comparison operation */
693 int dest
, /* Write results into this register */
694 u8 op
, /* Comparison operator */
695 u8 p5
/* SQLITE_NULLEQ or zero */
697 Vdbe
*v
= pParse
->pVdbe
;
698 Expr
*pLeft
= pExpr
->pLeft
;
699 Expr
*pRight
= pExpr
->pRight
;
700 int nLeft
= sqlite3ExprVectorSize(pLeft
);
706 int addrDone
= sqlite3VdbeMakeLabel(pParse
);
707 int isCommuted
= ExprHasProperty(pExpr
,EP_Commuted
);
709 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
710 if( pParse
->nErr
) return;
711 if( nLeft
!=sqlite3ExprVectorSize(pRight
) ){
712 sqlite3ErrorMsg(pParse
, "row value misused");
715 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_NE
716 || pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
717 || pExpr
->op
==TK_LT
|| pExpr
->op
==TK_GT
718 || pExpr
->op
==TK_LE
|| pExpr
->op
==TK_GE
720 assert( pExpr
->op
==op
|| (pExpr
->op
==TK_IS
&& op
==TK_EQ
)
721 || (pExpr
->op
==TK_ISNOT
&& op
==TK_NE
) );
722 assert( p5
==0 || pExpr
->op
!=op
);
723 assert( p5
==SQLITE_NULLEQ
|| pExpr
->op
==op
);
725 if( op
==TK_LE
) opx
= TK_LT
;
726 if( op
==TK_GE
) opx
= TK_GT
;
727 if( op
==TK_NE
) opx
= TK_EQ
;
729 regLeft
= exprCodeSubselect(pParse
, pLeft
);
730 regRight
= exprCodeSubselect(pParse
, pRight
);
732 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, dest
);
733 for(i
=0; 1 /*Loop exits by "break"*/; i
++){
734 int regFree1
= 0, regFree2
= 0;
735 Expr
*pL
= 0, *pR
= 0;
737 assert( i
>=0 && i
<nLeft
);
738 if( addrCmp
) sqlite3VdbeJumpHere(v
, addrCmp
);
739 r1
= exprVectorRegister(pParse
, pLeft
, i
, regLeft
, &pL
, ®Free1
);
740 r2
= exprVectorRegister(pParse
, pRight
, i
, regRight
, &pR
, ®Free2
);
741 addrCmp
= sqlite3VdbeCurrentAddr(v
);
742 codeCompare(pParse
, pL
, pR
, opx
, r1
, r2
, addrDone
, p5
, isCommuted
);
743 testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
744 testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
745 testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
746 testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
747 testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
748 testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
749 sqlite3ReleaseTempReg(pParse
, regFree1
);
750 sqlite3ReleaseTempReg(pParse
, regFree2
);
751 if( (opx
==TK_LT
|| opx
==TK_GT
) && i
<nLeft
-1 ){
752 addrCmp
= sqlite3VdbeAddOp0(v
, OP_ElseEq
);
753 testcase(opx
==TK_LT
); VdbeCoverageIf(v
,opx
==TK_LT
);
754 testcase(opx
==TK_GT
); VdbeCoverageIf(v
,opx
==TK_GT
);
756 if( p5
==SQLITE_NULLEQ
){
757 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
);
759 sqlite3VdbeAddOp3(v
, OP_ZeroOrNull
, r1
, dest
, r2
);
765 sqlite3VdbeAddOp2(v
, OP_NotNull
, dest
, addrDone
); VdbeCoverage(v
);
767 assert( op
==TK_LT
|| op
==TK_GT
|| op
==TK_LE
|| op
==TK_GE
);
768 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrDone
);
769 if( i
==nLeft
-2 ) opx
= op
;
772 sqlite3VdbeJumpHere(v
, addrCmp
);
773 sqlite3VdbeResolveLabel(v
, addrDone
);
775 sqlite3VdbeAddOp2(v
, OP_Not
, dest
, dest
);
779 #if SQLITE_MAX_EXPR_DEPTH>0
781 ** Check that argument nHeight is less than or equal to the maximum
782 ** expression depth allowed. If it is not, leave an error message in
785 int sqlite3ExprCheckHeight(Parse
*pParse
, int nHeight
){
787 int mxHeight
= pParse
->db
->aLimit
[SQLITE_LIMIT_EXPR_DEPTH
];
788 if( nHeight
>mxHeight
){
789 sqlite3ErrorMsg(pParse
,
790 "Expression tree is too large (maximum depth %d)", mxHeight
797 /* The following three functions, heightOfExpr(), heightOfExprList()
798 ** and heightOfSelect(), are used to determine the maximum height
799 ** of any expression tree referenced by the structure passed as the
802 ** If this maximum height is greater than the current value pointed
803 ** to by pnHeight, the second parameter, then set *pnHeight to that
806 static void heightOfExpr(const Expr
*p
, int *pnHeight
){
808 if( p
->nHeight
>*pnHeight
){
809 *pnHeight
= p
->nHeight
;
813 static void heightOfExprList(const ExprList
*p
, int *pnHeight
){
816 for(i
=0; i
<p
->nExpr
; i
++){
817 heightOfExpr(p
->a
[i
].pExpr
, pnHeight
);
821 static void heightOfSelect(const Select
*pSelect
, int *pnHeight
){
823 for(p
=pSelect
; p
; p
=p
->pPrior
){
824 heightOfExpr(p
->pWhere
, pnHeight
);
825 heightOfExpr(p
->pHaving
, pnHeight
);
826 heightOfExpr(p
->pLimit
, pnHeight
);
827 heightOfExprList(p
->pEList
, pnHeight
);
828 heightOfExprList(p
->pGroupBy
, pnHeight
);
829 heightOfExprList(p
->pOrderBy
, pnHeight
);
834 ** Set the Expr.nHeight variable in the structure passed as an
835 ** argument. An expression with no children, Expr.pList or
836 ** Expr.pSelect member has a height of 1. Any other expression
837 ** has a height equal to the maximum height of any other
838 ** referenced Expr plus one.
840 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
843 static void exprSetHeight(Expr
*p
){
844 int nHeight
= p
->pLeft
? p
->pLeft
->nHeight
: 0;
845 if( NEVER(p
->pRight
) && p
->pRight
->nHeight
>nHeight
){
846 nHeight
= p
->pRight
->nHeight
;
848 if( ExprUseXSelect(p
) ){
849 heightOfSelect(p
->x
.pSelect
, &nHeight
);
850 }else if( p
->x
.pList
){
851 heightOfExprList(p
->x
.pList
, &nHeight
);
852 p
->flags
|= EP_Propagate
& sqlite3ExprListFlags(p
->x
.pList
);
854 p
->nHeight
= nHeight
+ 1;
858 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
859 ** the height is greater than the maximum allowed expression depth,
860 ** leave an error in pParse.
862 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
865 void sqlite3ExprSetHeightAndFlags(Parse
*pParse
, Expr
*p
){
866 if( pParse
->nErr
) return;
868 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
872 ** Return the maximum height of any expression tree referenced
873 ** by the select statement passed as an argument.
875 int sqlite3SelectExprHeight(const Select
*p
){
877 heightOfSelect(p
, &nHeight
);
880 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
882 ** Propagate all EP_Propagate flags from the Expr.x.pList into
885 void sqlite3ExprSetHeightAndFlags(Parse
*pParse
, Expr
*p
){
886 if( pParse
->nErr
) return;
887 if( p
&& ExprUseXList(p
) && p
->x
.pList
){
888 p
->flags
|= EP_Propagate
& sqlite3ExprListFlags(p
->x
.pList
);
891 #define exprSetHeight(y)
892 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
895 ** Set the error offset for an Expr node, if possible.
897 void sqlite3ExprSetErrorOffset(Expr
*pExpr
, int iOfst
){
898 if( pExpr
==0 ) return;
899 if( NEVER(ExprUseWJoin(pExpr
)) ) return;
900 pExpr
->w
.iOfst
= iOfst
;
904 ** This routine is the core allocator for Expr nodes.
906 ** Construct a new expression node and return a pointer to it. Memory
907 ** for this node and for the pToken argument is a single allocation
908 ** obtained from sqlite3DbMalloc(). The calling function
909 ** is responsible for making sure the node eventually gets freed.
911 ** If dequote is true, then the token (if it exists) is dequoted.
912 ** If dequote is false, no dequoting is performed. The deQuote
913 ** parameter is ignored if pToken is NULL or if the token does not
914 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
915 ** then the EP_DblQuoted flag is set on the expression node.
917 ** Special case: If op==TK_INTEGER and pToken points to a string that
918 ** can be translated into a 32-bit integer, then the token is not
919 ** stored in u.zToken. Instead, the integer values is written
920 ** into u.iValue and the EP_IntValue flag is set. No extra storage
921 ** is allocated to hold the integer text and the dequote flag is ignored.
923 Expr
*sqlite3ExprAlloc(
924 sqlite3
*db
, /* Handle for sqlite3DbMallocRawNN() */
925 int op
, /* Expression opcode */
926 const Token
*pToken
, /* Token argument. Might be NULL */
927 int dequote
/* True to dequote */
935 if( op
!=TK_INTEGER
|| pToken
->z
==0
936 || sqlite3GetInt32(pToken
->z
, &iValue
)==0 ){
937 nExtra
= pToken
->n
+1;
941 pNew
= sqlite3DbMallocRawNN(db
, sizeof(Expr
)+nExtra
);
943 memset(pNew
, 0, sizeof(Expr
));
948 pNew
->flags
|= EP_IntValue
|EP_Leaf
|(iValue
?EP_IsTrue
:EP_IsFalse
);
949 pNew
->u
.iValue
= iValue
;
951 pNew
->u
.zToken
= (char*)&pNew
[1];
952 assert( pToken
->z
!=0 || pToken
->n
==0 );
953 if( pToken
->n
) memcpy(pNew
->u
.zToken
, pToken
->z
, pToken
->n
);
954 pNew
->u
.zToken
[pToken
->n
] = 0;
955 if( dequote
&& sqlite3Isquote(pNew
->u
.zToken
[0]) ){
956 sqlite3DequoteExpr(pNew
);
960 #if SQLITE_MAX_EXPR_DEPTH>0
968 ** Allocate a new expression node from a zero-terminated token that has
969 ** already been dequoted.
972 sqlite3
*db
, /* Handle for sqlite3DbMallocZero() (may be null) */
973 int op
, /* Expression opcode */
974 const char *zToken
/* Token argument. Might be NULL */
978 x
.n
= sqlite3Strlen30(zToken
);
979 return sqlite3ExprAlloc(db
, op
, &x
, 0);
983 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
985 ** If pRoot==NULL that means that a memory allocation error has occurred.
986 ** In that case, delete the subtrees pLeft and pRight.
988 void sqlite3ExprAttachSubtrees(
995 assert( db
->mallocFailed
);
996 sqlite3ExprDelete(db
, pLeft
);
997 sqlite3ExprDelete(db
, pRight
);
999 assert( ExprUseXList(pRoot
) );
1000 assert( pRoot
->x
.pSelect
==0 );
1002 pRoot
->pRight
= pRight
;
1003 pRoot
->flags
|= EP_Propagate
& pRight
->flags
;
1004 #if SQLITE_MAX_EXPR_DEPTH>0
1005 pRoot
->nHeight
= pRight
->nHeight
+1;
1011 pRoot
->pLeft
= pLeft
;
1012 pRoot
->flags
|= EP_Propagate
& pLeft
->flags
;
1013 #if SQLITE_MAX_EXPR_DEPTH>0
1014 if( pLeft
->nHeight
>=pRoot
->nHeight
){
1015 pRoot
->nHeight
= pLeft
->nHeight
+1;
1023 ** Allocate an Expr node which joins as many as two subtrees.
1025 ** One or both of the subtrees can be NULL. Return a pointer to the new
1026 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1027 ** free the subtrees and return NULL.
1030 Parse
*pParse
, /* Parsing context */
1031 int op
, /* Expression opcode */
1032 Expr
*pLeft
, /* Left operand */
1033 Expr
*pRight
/* Right operand */
1036 p
= sqlite3DbMallocRawNN(pParse
->db
, sizeof(Expr
));
1038 memset(p
, 0, sizeof(Expr
));
1041 sqlite3ExprAttachSubtrees(pParse
->db
, p
, pLeft
, pRight
);
1042 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
1044 sqlite3ExprDelete(pParse
->db
, pLeft
);
1045 sqlite3ExprDelete(pParse
->db
, pRight
);
1051 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1052 ** do a memory allocation failure) then delete the pSelect object.
1054 void sqlite3PExprAddSelect(Parse
*pParse
, Expr
*pExpr
, Select
*pSelect
){
1056 pExpr
->x
.pSelect
= pSelect
;
1057 ExprSetProperty(pExpr
, EP_xIsSelect
|EP_Subquery
);
1058 sqlite3ExprSetHeightAndFlags(pParse
, pExpr
);
1060 assert( pParse
->db
->mallocFailed
);
1061 sqlite3SelectDelete(pParse
->db
, pSelect
);
1066 ** Expression list pEList is a list of vector values. This function
1067 ** converts the contents of pEList to a VALUES(...) Select statement
1068 ** returning 1 row for each element of the list. For example, the
1071 ** ( (1,2), (3,4) (5,6) )
1073 ** is translated to the equivalent of:
1075 ** VALUES(1,2), (3,4), (5,6)
1077 ** Each of the vector values in pEList must contain exactly nElem terms.
1078 ** If a list element that is not a vector or does not contain nElem terms,
1079 ** an error message is left in pParse.
1081 ** This is used as part of processing IN(...) expressions with a list
1082 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1084 Select
*sqlite3ExprListToValues(Parse
*pParse
, int nElem
, ExprList
*pEList
){
1088 for(ii
=0; ii
<pEList
->nExpr
; ii
++){
1090 Expr
*pExpr
= pEList
->a
[ii
].pExpr
;
1092 if( pExpr
->op
==TK_VECTOR
){
1093 assert( ExprUseXList(pExpr
) );
1094 nExprElem
= pExpr
->x
.pList
->nExpr
;
1098 if( nExprElem
!=nElem
){
1099 sqlite3ErrorMsg(pParse
, "IN(...) element has %d term%s - expected %d",
1100 nExprElem
, nExprElem
>1?"s":"", nElem
1104 assert( ExprUseXList(pExpr
) );
1105 pSel
= sqlite3SelectNew(pParse
, pExpr
->x
.pList
, 0, 0, 0, 0, 0, SF_Values
,0);
1110 pSel
->pPrior
= pRet
;
1116 if( pRet
&& pRet
->pPrior
){
1117 pRet
->selFlags
|= SF_MultiValue
;
1119 sqlite3ExprListDelete(pParse
->db
, pEList
);
1124 ** Join two expressions using an AND operator. If either expression is
1125 ** NULL, then just return the other expression.
1127 ** If one side or the other of the AND is known to be false, and neither side
1128 ** is part of an ON clause, then instead of returning an AND expression,
1129 ** just return a constant expression with a value of false.
1131 Expr
*sqlite3ExprAnd(Parse
*pParse
, Expr
*pLeft
, Expr
*pRight
){
1132 sqlite3
*db
= pParse
->db
;
1135 }else if( pRight
==0 ){
1138 u32 f
= pLeft
->flags
| pRight
->flags
;
1139 if( (f
&(EP_OuterON
|EP_InnerON
|EP_IsFalse
))==EP_IsFalse
1140 && !IN_RENAME_OBJECT
1142 sqlite3ExprDeferredDelete(pParse
, pLeft
);
1143 sqlite3ExprDeferredDelete(pParse
, pRight
);
1144 return sqlite3Expr(db
, TK_INTEGER
, "0");
1146 return sqlite3PExpr(pParse
, TK_AND
, pLeft
, pRight
);
1152 ** Construct a new expression node for a function with multiple
1155 Expr
*sqlite3ExprFunction(
1156 Parse
*pParse
, /* Parsing context */
1157 ExprList
*pList
, /* Argument list */
1158 const Token
*pToken
, /* Name of the function */
1159 int eDistinct
/* SF_Distinct or SF_ALL or 0 */
1162 sqlite3
*db
= pParse
->db
;
1164 pNew
= sqlite3ExprAlloc(db
, TK_FUNCTION
, pToken
, 1);
1166 sqlite3ExprListDelete(db
, pList
); /* Avoid memory leak when malloc fails */
1169 assert( !ExprHasProperty(pNew
, EP_InnerON
|EP_OuterON
) );
1170 pNew
->w
.iOfst
= (int)(pToken
->z
- pParse
->zTail
);
1172 && pList
->nExpr
> pParse
->db
->aLimit
[SQLITE_LIMIT_FUNCTION_ARG
]
1175 sqlite3ErrorMsg(pParse
, "too many arguments on function %T", pToken
);
1177 pNew
->x
.pList
= pList
;
1178 ExprSetProperty(pNew
, EP_HasFunc
);
1179 assert( ExprUseXList(pNew
) );
1180 sqlite3ExprSetHeightAndFlags(pParse
, pNew
);
1181 if( eDistinct
==SF_Distinct
) ExprSetProperty(pNew
, EP_Distinct
);
1186 ** Report an error when attempting to use an ORDER BY clause within
1187 ** the arguments of a non-aggregate function.
1189 void sqlite3ExprOrderByAggregateError(Parse
*pParse
, Expr
*p
){
1190 sqlite3ErrorMsg(pParse
,
1191 "ORDER BY may not be used with non-aggregate %#T()", p
1196 ** Attach an ORDER BY clause to a function call.
1198 ** functionname( arguments ORDER BY sortlist )
1199 ** \_____________________/ \______/
1202 ** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER
1203 ** and added to the Expr.pLeft field of the parent TK_FUNCTION node.
1205 void sqlite3ExprAddFunctionOrderBy(
1206 Parse
*pParse
, /* Parsing context */
1207 Expr
*pExpr
, /* The function call to which ORDER BY is to be added */
1208 ExprList
*pOrderBy
/* The ORDER BY clause to add */
1211 sqlite3
*db
= pParse
->db
;
1212 if( NEVER(pOrderBy
==0) ){
1213 assert( db
->mallocFailed
);
1217 assert( db
->mallocFailed
);
1218 sqlite3ExprListDelete(db
, pOrderBy
);
1221 assert( pExpr
->op
==TK_FUNCTION
);
1222 assert( pExpr
->pLeft
==0 );
1223 assert( ExprUseXList(pExpr
) );
1224 if( pExpr
->x
.pList
==0 || NEVER(pExpr
->x
.pList
->nExpr
==0) ){
1225 /* Ignore ORDER BY on zero-argument aggregates */
1226 sqlite3ParserAddCleanup(pParse
, sqlite3ExprListDeleteGeneric
, pOrderBy
);
1229 if( IsWindowFunc(pExpr
) ){
1230 sqlite3ExprOrderByAggregateError(pParse
, pExpr
);
1231 sqlite3ExprListDelete(db
, pOrderBy
);
1235 pOB
= sqlite3ExprAlloc(db
, TK_ORDER
, 0, 0);
1237 sqlite3ExprListDelete(db
, pOrderBy
);
1240 pOB
->x
.pList
= pOrderBy
;
1241 assert( ExprUseXList(pOB
) );
1243 ExprSetProperty(pOB
, EP_FullSize
);
1247 ** Check to see if a function is usable according to current access
1250 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1252 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1255 ** If the function is not usable, create an error.
1257 void sqlite3ExprFunctionUsable(
1258 Parse
*pParse
, /* Parsing and code generating context */
1259 const Expr
*pExpr
, /* The function invocation */
1260 const FuncDef
*pDef
/* The function being invoked */
1262 assert( !IN_RENAME_OBJECT
);
1263 assert( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0 );
1264 if( ExprHasProperty(pExpr
, EP_FromDDL
) ){
1265 if( (pDef
->funcFlags
& SQLITE_FUNC_DIRECT
)!=0
1266 || (pParse
->db
->flags
& SQLITE_TrustedSchema
)==0
1268 /* Functions prohibited in triggers and views if:
1269 ** (1) tagged with SQLITE_DIRECTONLY
1270 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1271 ** is tagged with SQLITE_FUNC_UNSAFE) and
1272 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1273 ** that the schema is possibly tainted).
1275 sqlite3ErrorMsg(pParse
, "unsafe use of %#T()", pExpr
);
1281 ** Assign a variable number to an expression that encodes a wildcard
1282 ** in the original SQL statement.
1284 ** Wildcards consisting of a single "?" are assigned the next sequential
1287 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1288 ** sure "nnn" is not too big to avoid a denial of service attack when
1289 ** the SQL statement comes from an external source.
1291 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1292 ** as the previous instance of the same wildcard. Or if this is the first
1293 ** instance of the wildcard, the next sequential variable number is
1296 void sqlite3ExprAssignVarNumber(Parse
*pParse
, Expr
*pExpr
, u32 n
){
1297 sqlite3
*db
= pParse
->db
;
1301 if( pExpr
==0 ) return;
1302 assert( !ExprHasProperty(pExpr
, EP_IntValue
|EP_Reduced
|EP_TokenOnly
) );
1303 z
= pExpr
->u
.zToken
;
1306 assert( n
==(u32
)sqlite3Strlen30(z
) );
1308 /* Wildcard of the form "?". Assign the next variable number */
1309 assert( z
[0]=='?' );
1310 x
= (ynVar
)(++pParse
->nVar
);
1314 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1315 ** use it as the variable number */
1318 if( n
==2 ){ /*OPTIMIZATION-IF-TRUE*/
1319 i
= z
[1]-'0'; /* The common case of ?N for a single digit N */
1322 bOk
= 0==sqlite3Atoi64(&z
[1], &i
, n
-1, SQLITE_UTF8
);
1326 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]-1 );
1327 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] );
1328 if( bOk
==0 || i
<1 || i
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
1329 sqlite3ErrorMsg(pParse
, "variable number must be between ?1 and ?%d",
1330 db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]);
1331 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1335 if( x
>pParse
->nVar
){
1336 pParse
->nVar
= (int)x
;
1338 }else if( sqlite3VListNumToName(pParse
->pVList
, x
)==0 ){
1342 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1343 ** number as the prior appearance of the same name, or if the name
1344 ** has never appeared before, reuse the same variable number
1346 x
= (ynVar
)sqlite3VListNameToNum(pParse
->pVList
, z
, n
);
1348 x
= (ynVar
)(++pParse
->nVar
);
1353 pParse
->pVList
= sqlite3VListAdd(db
, pParse
->pVList
, z
, n
, x
);
1357 if( x
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
1358 sqlite3ErrorMsg(pParse
, "too many SQL variables");
1359 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1364 ** Recursively delete an expression tree.
1366 static SQLITE_NOINLINE
void sqlite3ExprDeleteNN(sqlite3
*db
, Expr
*p
){
1369 assert( !ExprUseUValue(p
) || p
->u
.iValue
>=0 );
1370 assert( !ExprUseYWin(p
) || !ExprUseYSub(p
) );
1371 assert( !ExprUseYWin(p
) || p
->y
.pWin
!=0 || db
->mallocFailed
);
1372 assert( p
->op
!=TK_FUNCTION
|| !ExprUseYSub(p
) );
1374 if( ExprHasProperty(p
, EP_Leaf
) && !ExprHasProperty(p
, EP_TokenOnly
) ){
1375 assert( p
->pLeft
==0 );
1376 assert( p
->pRight
==0 );
1377 assert( !ExprUseXSelect(p
) || p
->x
.pSelect
==0 );
1378 assert( !ExprUseXList(p
) || p
->x
.pList
==0 );
1381 if( !ExprHasProperty(p
, (EP_TokenOnly
|EP_Leaf
)) ){
1382 /* The Expr.x union is never used at the same time as Expr.pRight */
1383 assert( (ExprUseXList(p
) && p
->x
.pList
==0) || p
->pRight
==0 );
1384 if( p
->pLeft
&& p
->op
!=TK_SELECT_COLUMN
) sqlite3ExprDeleteNN(db
, p
->pLeft
);
1386 assert( !ExprHasProperty(p
, EP_WinFunc
) );
1387 sqlite3ExprDeleteNN(db
, p
->pRight
);
1388 }else if( ExprUseXSelect(p
) ){
1389 assert( !ExprHasProperty(p
, EP_WinFunc
) );
1390 sqlite3SelectDelete(db
, p
->x
.pSelect
);
1392 sqlite3ExprListDelete(db
, p
->x
.pList
);
1393 #ifndef SQLITE_OMIT_WINDOWFUNC
1394 if( ExprHasProperty(p
, EP_WinFunc
) ){
1395 sqlite3WindowDelete(db
, p
->y
.pWin
);
1400 if( !ExprHasProperty(p
, EP_Static
) ){
1401 sqlite3DbNNFreeNN(db
, p
);
1404 void sqlite3ExprDelete(sqlite3
*db
, Expr
*p
){
1405 if( p
) sqlite3ExprDeleteNN(db
, p
);
1407 void sqlite3ExprDeleteGeneric(sqlite3
*db
, void *p
){
1408 if( ALWAYS(p
) ) sqlite3ExprDeleteNN(db
, (Expr
*)p
);
1412 ** Clear both elements of an OnOrUsing object
1414 void sqlite3ClearOnOrUsing(sqlite3
*db
, OnOrUsing
*p
){
1416 /* Nothing to clear */
1418 sqlite3ExprDeleteNN(db
, p
->pOn
);
1419 }else if( p
->pUsing
){
1420 sqlite3IdListDelete(db
, p
->pUsing
);
1425 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1426 ** This is similar to sqlite3ExprDelete() except that the delete is
1427 ** deferred until the pParse is deleted.
1429 ** The pExpr might be deleted immediately on an OOM error.
1431 ** The deferred delete is (currently) implemented by adding the
1432 ** pExpr to the pParse->pConstExpr list with a register number of 0.
1434 void sqlite3ExprDeferredDelete(Parse
*pParse
, Expr
*pExpr
){
1435 sqlite3ParserAddCleanup(pParse
, sqlite3ExprDeleteGeneric
, pExpr
);
1438 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1441 void sqlite3ExprUnmapAndDelete(Parse
*pParse
, Expr
*p
){
1443 if( IN_RENAME_OBJECT
){
1444 sqlite3RenameExprUnmap(pParse
, p
);
1446 sqlite3ExprDeleteNN(pParse
->db
, p
);
1451 ** Return the number of bytes allocated for the expression structure
1452 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1453 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1455 static int exprStructSize(const Expr
*p
){
1456 if( ExprHasProperty(p
, EP_TokenOnly
) ) return EXPR_TOKENONLYSIZE
;
1457 if( ExprHasProperty(p
, EP_Reduced
) ) return EXPR_REDUCEDSIZE
;
1458 return EXPR_FULLSIZE
;
1462 ** The dupedExpr*Size() routines each return the number of bytes required
1463 ** to store a copy of an expression or expression tree. They differ in
1464 ** how much of the tree is measured.
1466 ** dupedExprStructSize() Size of only the Expr structure
1467 ** dupedExprNodeSize() Size of Expr + space for token
1468 ** dupedExprSize() Expr + token + subtree components
1470 ***************************************************************************
1472 ** The dupedExprStructSize() function returns two values OR-ed together:
1473 ** (1) the space required for a copy of the Expr structure only and
1474 ** (2) the EP_xxx flags that indicate what the structure size should be.
1475 ** The return values is always one of:
1478 ** EXPR_REDUCEDSIZE | EP_Reduced
1479 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1481 ** The size of the structure can be found by masking the return value
1482 ** of this routine with 0xfff. The flags can be found by masking the
1483 ** return value with EP_Reduced|EP_TokenOnly.
1485 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1486 ** (unreduced) Expr objects as they or originally constructed by the parser.
1487 ** During expression analysis, extra information is computed and moved into
1488 ** later parts of the Expr object and that extra information might get chopped
1489 ** off if the expression is reduced. Note also that it does not work to
1490 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1491 ** to reduce a pristine expression tree from the parser. The implementation
1492 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1493 ** to enforce this constraint.
1495 static int dupedExprStructSize(const Expr
*p
, int flags
){
1497 assert( flags
==EXPRDUP_REDUCE
|| flags
==0 ); /* Only one flag value allowed */
1498 assert( EXPR_FULLSIZE
<=0xfff );
1499 assert( (0xfff & (EP_Reduced
|EP_TokenOnly
))==0 );
1500 if( 0==flags
|| ExprHasProperty(p
, EP_FullSize
) ){
1501 nSize
= EXPR_FULLSIZE
;
1503 assert( !ExprHasProperty(p
, EP_TokenOnly
|EP_Reduced
) );
1504 assert( !ExprHasProperty(p
, EP_OuterON
) );
1505 assert( !ExprHasVVAProperty(p
, EP_NoReduce
) );
1506 if( p
->pLeft
|| p
->x
.pList
){
1507 nSize
= EXPR_REDUCEDSIZE
| EP_Reduced
;
1509 assert( p
->pRight
==0 );
1510 nSize
= EXPR_TOKENONLYSIZE
| EP_TokenOnly
;
1517 ** This function returns the space in bytes required to store the copy
1518 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1519 ** string is defined.)
1521 static int dupedExprNodeSize(const Expr
*p
, int flags
){
1522 int nByte
= dupedExprStructSize(p
, flags
) & 0xfff;
1523 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1524 nByte
+= sqlite3Strlen30NN(p
->u
.zToken
)+1;
1526 return ROUND8(nByte
);
1530 ** Return the number of bytes required to create a duplicate of the
1531 ** expression passed as the first argument.
1533 ** The value returned includes space to create a copy of the Expr struct
1534 ** itself and the buffer referred to by Expr.u.zToken, if any.
1536 ** The return value includes space to duplicate all Expr nodes in the
1537 ** tree formed by Expr.pLeft and Expr.pRight, but not any other
1538 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
1540 static int dupedExprSize(const Expr
*p
){
1543 nByte
= dupedExprNodeSize(p
, EXPRDUP_REDUCE
);
1544 if( p
->pLeft
) nByte
+= dupedExprSize(p
->pLeft
);
1545 if( p
->pRight
) nByte
+= dupedExprSize(p
->pRight
);
1546 assert( nByte
==ROUND8(nByte
) );
1551 ** An EdupBuf is a memory allocation used to stored multiple Expr objects
1552 ** together with their Expr.zToken content. This is used to help implement
1553 ** compression while doing sqlite3ExprDup(). The top-level Expr does the
1554 ** allocation for itself and many of its decendents, then passes an instance
1555 ** of the structure down into exprDup() so that they decendents can have
1556 ** access to that memory.
1558 typedef struct EdupBuf EdupBuf
;
1560 u8
*zAlloc
; /* Memory space available for storage */
1562 u8
*zEnd
; /* First byte past the end of memory */
1567 ** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
1568 ** is not NULL then it points to memory that can be used to store a copy
1569 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf
1570 ** is updated with the new buffer tail prior to returning.
1572 static Expr
*exprDup(
1573 sqlite3
*db
, /* Database connection (for memory allocation) */
1574 const Expr
*p
, /* Expr tree to be duplicated */
1575 int dupFlags
, /* EXPRDUP_REDUCE for compression. 0 if not */
1576 EdupBuf
*pEdupBuf
/* Preallocated storage space, or NULL */
1578 Expr
*pNew
; /* Value to return */
1579 EdupBuf sEdupBuf
; /* Memory space from which to build Expr object */
1580 u32 staticFlag
; /* EP_Static if space not obtained from malloc */
1581 int nToken
= -1; /* Space needed for p->u.zToken. -1 means unknown */
1585 assert( dupFlags
==0 || dupFlags
==EXPRDUP_REDUCE
);
1586 assert( pEdupBuf
==0 || dupFlags
==EXPRDUP_REDUCE
);
1588 /* Figure out where to write the new Expr structure. */
1590 sEdupBuf
.zAlloc
= pEdupBuf
->zAlloc
;
1592 sEdupBuf
.zEnd
= pEdupBuf
->zEnd
;
1594 staticFlag
= EP_Static
;
1595 assert( sEdupBuf
.zAlloc
!=0 );
1596 assert( dupFlags
==EXPRDUP_REDUCE
);
1600 nAlloc
= dupedExprSize(p
);
1601 }else if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1602 nToken
= sqlite3Strlen30NN(p
->u
.zToken
)+1;
1603 nAlloc
= ROUND8(EXPR_FULLSIZE
+ nToken
);
1606 nAlloc
= ROUND8(EXPR_FULLSIZE
);
1608 assert( nAlloc
==ROUND8(nAlloc
) );
1609 sEdupBuf
.zAlloc
= sqlite3DbMallocRawNN(db
, nAlloc
);
1611 sEdupBuf
.zEnd
= sEdupBuf
.zAlloc
? sEdupBuf
.zAlloc
+nAlloc
: 0;
1616 pNew
= (Expr
*)sEdupBuf
.zAlloc
;
1617 assert( EIGHT_BYTE_ALIGNMENT(pNew
) );
1620 /* Set nNewSize to the size allocated for the structure pointed to
1621 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1622 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1623 ** by the copy of the p->u.zToken string (if any).
1625 const unsigned nStructSize
= dupedExprStructSize(p
, dupFlags
);
1626 int nNewSize
= nStructSize
& 0xfff;
1628 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1629 nToken
= sqlite3Strlen30(p
->u
.zToken
) + 1;
1635 assert( (int)(sEdupBuf
.zEnd
- sEdupBuf
.zAlloc
) >= nNewSize
+nToken
);
1636 assert( ExprHasProperty(p
, EP_Reduced
)==0 );
1637 memcpy(sEdupBuf
.zAlloc
, p
, nNewSize
);
1639 u32 nSize
= (u32
)exprStructSize(p
);
1640 assert( (int)(sEdupBuf
.zEnd
- sEdupBuf
.zAlloc
) >=
1641 (int)EXPR_FULLSIZE
+nToken
);
1642 memcpy(sEdupBuf
.zAlloc
, p
, nSize
);
1643 if( nSize
<EXPR_FULLSIZE
){
1644 memset(&sEdupBuf
.zAlloc
[nSize
], 0, EXPR_FULLSIZE
-nSize
);
1646 nNewSize
= EXPR_FULLSIZE
;
1649 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1650 pNew
->flags
&= ~(EP_Reduced
|EP_TokenOnly
|EP_Static
);
1651 pNew
->flags
|= nStructSize
& (EP_Reduced
|EP_TokenOnly
);
1652 pNew
->flags
|= staticFlag
;
1653 ExprClearVVAProperties(pNew
);
1655 ExprSetVVAProperty(pNew
, EP_Immutable
);
1658 /* Copy the p->u.zToken string, if any. */
1659 assert( nToken
>=0 );
1661 char *zToken
= pNew
->u
.zToken
= (char*)&sEdupBuf
.zAlloc
[nNewSize
];
1662 memcpy(zToken
, p
->u
.zToken
, nToken
);
1665 sEdupBuf
.zAlloc
+= ROUND8(nNewSize
);
1667 if( ((p
->flags
|pNew
->flags
)&(EP_TokenOnly
|EP_Leaf
))==0 ){
1669 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1670 if( ExprUseXSelect(p
) ){
1671 pNew
->x
.pSelect
= sqlite3SelectDup(db
, p
->x
.pSelect
, dupFlags
);
1673 pNew
->x
.pList
= sqlite3ExprListDup(db
, p
->x
.pList
,
1674 p
->op
!=TK_ORDER
? dupFlags
: 0);
1677 #ifndef SQLITE_OMIT_WINDOWFUNC
1678 if( ExprHasProperty(p
, EP_WinFunc
) ){
1679 pNew
->y
.pWin
= sqlite3WindowDup(db
, pNew
, p
->y
.pWin
);
1680 assert( ExprHasProperty(pNew
, EP_WinFunc
) );
1682 #endif /* SQLITE_OMIT_WINDOWFUNC */
1684 /* Fill in pNew->pLeft and pNew->pRight. */
1686 if( p
->op
==TK_SELECT_COLUMN
){
1687 pNew
->pLeft
= p
->pLeft
;
1688 assert( p
->pRight
==0
1689 || p
->pRight
==p
->pLeft
1690 || ExprHasProperty(p
->pLeft
, EP_Subquery
) );
1692 pNew
->pLeft
= p
->pLeft
?
1693 exprDup(db
, p
->pLeft
, EXPRDUP_REDUCE
, &sEdupBuf
) : 0;
1695 pNew
->pRight
= p
->pRight
?
1696 exprDup(db
, p
->pRight
, EXPRDUP_REDUCE
, &sEdupBuf
) : 0;
1698 if( p
->op
==TK_SELECT_COLUMN
){
1699 pNew
->pLeft
= p
->pLeft
;
1700 assert( p
->pRight
==0
1701 || p
->pRight
==p
->pLeft
1702 || ExprHasProperty(p
->pLeft
, EP_Subquery
) );
1704 pNew
->pLeft
= sqlite3ExprDup(db
, p
->pLeft
, 0);
1706 pNew
->pRight
= sqlite3ExprDup(db
, p
->pRight
, 0);
1710 if( pEdupBuf
) memcpy(pEdupBuf
, &sEdupBuf
, sizeof(sEdupBuf
));
1711 assert( sEdupBuf
.zAlloc
<= sEdupBuf
.zEnd
);
1716 ** Create and return a deep copy of the object passed as the second
1717 ** argument. If an OOM condition is encountered, NULL is returned
1718 ** and the db->mallocFailed flag set.
1720 #ifndef SQLITE_OMIT_CTE
1721 With
*sqlite3WithDup(sqlite3
*db
, With
*p
){
1724 sqlite3_int64 nByte
= sizeof(*p
) + sizeof(p
->a
[0]) * (p
->nCte
-1);
1725 pRet
= sqlite3DbMallocZero(db
, nByte
);
1728 pRet
->nCte
= p
->nCte
;
1729 for(i
=0; i
<p
->nCte
; i
++){
1730 pRet
->a
[i
].pSelect
= sqlite3SelectDup(db
, p
->a
[i
].pSelect
, 0);
1731 pRet
->a
[i
].pCols
= sqlite3ExprListDup(db
, p
->a
[i
].pCols
, 0);
1732 pRet
->a
[i
].zName
= sqlite3DbStrDup(db
, p
->a
[i
].zName
);
1733 pRet
->a
[i
].eM10d
= p
->a
[i
].eM10d
;
1740 # define sqlite3WithDup(x,y) 0
1743 #ifndef SQLITE_OMIT_WINDOWFUNC
1745 ** The gatherSelectWindows() procedure and its helper routine
1746 ** gatherSelectWindowsCallback() are used to scan all the expressions
1747 ** an a newly duplicated SELECT statement and gather all of the Window
1748 ** objects found there, assembling them onto the linked list at Select->pWin.
1750 static int gatherSelectWindowsCallback(Walker
*pWalker
, Expr
*pExpr
){
1751 if( pExpr
->op
==TK_FUNCTION
&& ExprHasProperty(pExpr
, EP_WinFunc
) ){
1752 Select
*pSelect
= pWalker
->u
.pSelect
;
1753 Window
*pWin
= pExpr
->y
.pWin
;
1755 assert( IsWindowFunc(pExpr
) );
1756 assert( pWin
->ppThis
==0 );
1757 sqlite3WindowLink(pSelect
, pWin
);
1759 return WRC_Continue
;
1761 static int gatherSelectWindowsSelectCallback(Walker
*pWalker
, Select
*p
){
1762 return p
==pWalker
->u
.pSelect
? WRC_Continue
: WRC_Prune
;
1764 static void gatherSelectWindows(Select
*p
){
1766 w
.xExprCallback
= gatherSelectWindowsCallback
;
1767 w
.xSelectCallback
= gatherSelectWindowsSelectCallback
;
1768 w
.xSelectCallback2
= 0;
1771 sqlite3WalkSelect(&w
, p
);
1777 ** The following group of routines make deep copies of expressions,
1778 ** expression lists, ID lists, and select statements. The copies can
1779 ** be deleted (by being passed to their respective ...Delete() routines)
1780 ** without effecting the originals.
1782 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1783 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1784 ** by subsequent calls to sqlite*ListAppend() routines.
1786 ** Any tables that the SrcList might point to are not duplicated.
1788 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1789 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1790 ** truncated version of the usual Expr structure that will be stored as
1791 ** part of the in-memory representation of the database schema.
1793 Expr
*sqlite3ExprDup(sqlite3
*db
, const Expr
*p
, int flags
){
1794 assert( flags
==0 || flags
==EXPRDUP_REDUCE
);
1795 return p
? exprDup(db
, p
, flags
, 0) : 0;
1797 ExprList
*sqlite3ExprListDup(sqlite3
*db
, const ExprList
*p
, int flags
){
1799 struct ExprList_item
*pItem
;
1800 const struct ExprList_item
*pOldItem
;
1802 Expr
*pPriorSelectColOld
= 0;
1803 Expr
*pPriorSelectColNew
= 0;
1805 if( p
==0 ) return 0;
1806 pNew
= sqlite3DbMallocRawNN(db
, sqlite3DbMallocSize(db
, p
));
1807 if( pNew
==0 ) return 0;
1808 pNew
->nExpr
= p
->nExpr
;
1809 pNew
->nAlloc
= p
->nAlloc
;
1812 for(i
=0; i
<p
->nExpr
; i
++, pItem
++, pOldItem
++){
1813 Expr
*pOldExpr
= pOldItem
->pExpr
;
1815 pItem
->pExpr
= sqlite3ExprDup(db
, pOldExpr
, flags
);
1817 && pOldExpr
->op
==TK_SELECT_COLUMN
1818 && (pNewExpr
= pItem
->pExpr
)!=0
1820 if( pNewExpr
->pRight
){
1821 pPriorSelectColOld
= pOldExpr
->pRight
;
1822 pPriorSelectColNew
= pNewExpr
->pRight
;
1823 pNewExpr
->pLeft
= pNewExpr
->pRight
;
1825 if( pOldExpr
->pLeft
!=pPriorSelectColOld
){
1826 pPriorSelectColOld
= pOldExpr
->pLeft
;
1827 pPriorSelectColNew
= sqlite3ExprDup(db
, pPriorSelectColOld
, flags
);
1828 pNewExpr
->pRight
= pPriorSelectColNew
;
1830 pNewExpr
->pLeft
= pPriorSelectColNew
;
1833 pItem
->zEName
= sqlite3DbStrDup(db
, pOldItem
->zEName
);
1834 pItem
->fg
= pOldItem
->fg
;
1836 pItem
->u
= pOldItem
->u
;
1842 ** If cursors, triggers, views and subqueries are all omitted from
1843 ** the build, then none of the following routines, except for
1844 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1845 ** called with a NULL argument.
1847 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1848 || !defined(SQLITE_OMIT_SUBQUERY)
1849 SrcList
*sqlite3SrcListDup(sqlite3
*db
, const SrcList
*p
, int flags
){
1854 if( p
==0 ) return 0;
1855 nByte
= sizeof(*p
) + (p
->nSrc
>0 ? sizeof(p
->a
[0]) * (p
->nSrc
-1) : 0);
1856 pNew
= sqlite3DbMallocRawNN(db
, nByte
);
1857 if( pNew
==0 ) return 0;
1858 pNew
->nSrc
= pNew
->nAlloc
= p
->nSrc
;
1859 for(i
=0; i
<p
->nSrc
; i
++){
1860 SrcItem
*pNewItem
= &pNew
->a
[i
];
1861 const SrcItem
*pOldItem
= &p
->a
[i
];
1863 pNewItem
->pSchema
= pOldItem
->pSchema
;
1864 pNewItem
->zDatabase
= sqlite3DbStrDup(db
, pOldItem
->zDatabase
);
1865 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1866 pNewItem
->zAlias
= sqlite3DbStrDup(db
, pOldItem
->zAlias
);
1867 pNewItem
->fg
= pOldItem
->fg
;
1868 pNewItem
->iCursor
= pOldItem
->iCursor
;
1869 pNewItem
->addrFillSub
= pOldItem
->addrFillSub
;
1870 pNewItem
->regReturn
= pOldItem
->regReturn
;
1871 if( pNewItem
->fg
.isIndexedBy
){
1872 pNewItem
->u1
.zIndexedBy
= sqlite3DbStrDup(db
, pOldItem
->u1
.zIndexedBy
);
1874 pNewItem
->u2
= pOldItem
->u2
;
1875 if( pNewItem
->fg
.isCte
){
1876 pNewItem
->u2
.pCteUse
->nUse
++;
1878 if( pNewItem
->fg
.isTabFunc
){
1879 pNewItem
->u1
.pFuncArg
=
1880 sqlite3ExprListDup(db
, pOldItem
->u1
.pFuncArg
, flags
);
1882 pTab
= pNewItem
->pTab
= pOldItem
->pTab
;
1886 pNewItem
->pSelect
= sqlite3SelectDup(db
, pOldItem
->pSelect
, flags
);
1887 if( pOldItem
->fg
.isUsing
){
1888 assert( pNewItem
->fg
.isUsing
);
1889 pNewItem
->u3
.pUsing
= sqlite3IdListDup(db
, pOldItem
->u3
.pUsing
);
1891 pNewItem
->u3
.pOn
= sqlite3ExprDup(db
, pOldItem
->u3
.pOn
, flags
);
1893 pNewItem
->colUsed
= pOldItem
->colUsed
;
1897 IdList
*sqlite3IdListDup(sqlite3
*db
, const IdList
*p
){
1901 if( p
==0 ) return 0;
1902 assert( p
->eU4
!=EU4_EXPR
);
1903 pNew
= sqlite3DbMallocRawNN(db
, sizeof(*pNew
)+(p
->nId
-1)*sizeof(p
->a
[0]) );
1904 if( pNew
==0 ) return 0;
1907 for(i
=0; i
<p
->nId
; i
++){
1908 struct IdList_item
*pNewItem
= &pNew
->a
[i
];
1909 const struct IdList_item
*pOldItem
= &p
->a
[i
];
1910 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1911 pNewItem
->u4
= pOldItem
->u4
;
1915 Select
*sqlite3SelectDup(sqlite3
*db
, const Select
*pDup
, int flags
){
1918 Select
**pp
= &pRet
;
1922 for(p
=pDup
; p
; p
=p
->pPrior
){
1923 Select
*pNew
= sqlite3DbMallocRawNN(db
, sizeof(*p
) );
1924 if( pNew
==0 ) break;
1925 pNew
->pEList
= sqlite3ExprListDup(db
, p
->pEList
, flags
);
1926 pNew
->pSrc
= sqlite3SrcListDup(db
, p
->pSrc
, flags
);
1927 pNew
->pWhere
= sqlite3ExprDup(db
, p
->pWhere
, flags
);
1928 pNew
->pGroupBy
= sqlite3ExprListDup(db
, p
->pGroupBy
, flags
);
1929 pNew
->pHaving
= sqlite3ExprDup(db
, p
->pHaving
, flags
);
1930 pNew
->pOrderBy
= sqlite3ExprListDup(db
, p
->pOrderBy
, flags
);
1932 pNew
->pNext
= pNext
;
1934 pNew
->pLimit
= sqlite3ExprDup(db
, p
->pLimit
, flags
);
1937 pNew
->selFlags
= p
->selFlags
& ~SF_UsesEphemeral
;
1938 pNew
->addrOpenEphm
[0] = -1;
1939 pNew
->addrOpenEphm
[1] = -1;
1940 pNew
->nSelectRow
= p
->nSelectRow
;
1941 pNew
->pWith
= sqlite3WithDup(db
, p
->pWith
);
1942 #ifndef SQLITE_OMIT_WINDOWFUNC
1944 pNew
->pWinDefn
= sqlite3WindowListDup(db
, p
->pWinDefn
);
1945 if( p
->pWin
&& db
->mallocFailed
==0 ) gatherSelectWindows(pNew
);
1947 pNew
->selId
= p
->selId
;
1948 if( db
->mallocFailed
){
1949 /* Any prior OOM might have left the Select object incomplete.
1950 ** Delete the whole thing rather than allow an incomplete Select
1951 ** to be used by the code generator. */
1953 sqlite3SelectDelete(db
, pNew
);
1964 Select
*sqlite3SelectDup(sqlite3
*db
, const Select
*p
, int flags
){
1972 ** Add a new element to the end of an expression list. If pList is
1973 ** initially NULL, then create a new expression list.
1975 ** The pList argument must be either NULL or a pointer to an ExprList
1976 ** obtained from a prior call to sqlite3ExprListAppend().
1978 ** If a memory allocation error occurs, the entire list is freed and
1979 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1980 ** that the new entry was successfully appended.
1982 static const struct ExprList_item zeroItem
= {0};
1983 SQLITE_NOINLINE ExprList
*sqlite3ExprListAppendNew(
1984 sqlite3
*db
, /* Database handle. Used for memory allocation */
1985 Expr
*pExpr
/* Expression to be appended. Might be NULL */
1987 struct ExprList_item
*pItem
;
1990 pList
= sqlite3DbMallocRawNN(db
, sizeof(ExprList
)+sizeof(pList
->a
[0])*4 );
1992 sqlite3ExprDelete(db
, pExpr
);
1997 pItem
= &pList
->a
[0];
1999 pItem
->pExpr
= pExpr
;
2002 SQLITE_NOINLINE ExprList
*sqlite3ExprListAppendGrow(
2003 sqlite3
*db
, /* Database handle. Used for memory allocation */
2004 ExprList
*pList
, /* List to which to append. Might be NULL */
2005 Expr
*pExpr
/* Expression to be appended. Might be NULL */
2007 struct ExprList_item
*pItem
;
2010 pNew
= sqlite3DbRealloc(db
, pList
,
2011 sizeof(*pList
)+(pList
->nAlloc
-1)*sizeof(pList
->a
[0]));
2013 sqlite3ExprListDelete(db
, pList
);
2014 sqlite3ExprDelete(db
, pExpr
);
2019 pItem
= &pList
->a
[pList
->nExpr
++];
2021 pItem
->pExpr
= pExpr
;
2024 ExprList
*sqlite3ExprListAppend(
2025 Parse
*pParse
, /* Parsing context */
2026 ExprList
*pList
, /* List to which to append. Might be NULL */
2027 Expr
*pExpr
/* Expression to be appended. Might be NULL */
2029 struct ExprList_item
*pItem
;
2031 return sqlite3ExprListAppendNew(pParse
->db
,pExpr
);
2033 if( pList
->nAlloc
<pList
->nExpr
+1 ){
2034 return sqlite3ExprListAppendGrow(pParse
->db
,pList
,pExpr
);
2036 pItem
= &pList
->a
[pList
->nExpr
++];
2038 pItem
->pExpr
= pExpr
;
2043 ** pColumns and pExpr form a vector assignment which is part of the SET
2044 ** clause of an UPDATE statement. Like this:
2046 ** (a,b,c) = (expr1,expr2,expr3)
2047 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
2049 ** For each term of the vector assignment, append new entries to the
2050 ** expression list pList. In the case of a subquery on the RHS, append
2051 ** TK_SELECT_COLUMN expressions.
2053 ExprList
*sqlite3ExprListAppendVector(
2054 Parse
*pParse
, /* Parsing context */
2055 ExprList
*pList
, /* List to which to append. Might be NULL */
2056 IdList
*pColumns
, /* List of names of LHS of the assignment */
2057 Expr
*pExpr
/* Vector expression to be appended. Might be NULL */
2059 sqlite3
*db
= pParse
->db
;
2062 int iFirst
= pList
? pList
->nExpr
: 0;
2063 /* pColumns can only be NULL due to an OOM but an OOM will cause an
2064 ** exit prior to this routine being invoked */
2065 if( NEVER(pColumns
==0) ) goto vector_append_error
;
2066 if( pExpr
==0 ) goto vector_append_error
;
2068 /* If the RHS is a vector, then we can immediately check to see that
2069 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
2070 ** wildcards ("*") in the result set of the SELECT must be expanded before
2071 ** we can do the size check, so defer the size check until code generation.
2073 if( pExpr
->op
!=TK_SELECT
&& pColumns
->nId
!=(n
=sqlite3ExprVectorSize(pExpr
)) ){
2074 sqlite3ErrorMsg(pParse
, "%d columns assigned %d values",
2076 goto vector_append_error
;
2079 for(i
=0; i
<pColumns
->nId
; i
++){
2080 Expr
*pSubExpr
= sqlite3ExprForVectorField(pParse
, pExpr
, i
, pColumns
->nId
);
2081 assert( pSubExpr
!=0 || db
->mallocFailed
);
2082 if( pSubExpr
==0 ) continue;
2083 pList
= sqlite3ExprListAppend(pParse
, pList
, pSubExpr
);
2085 assert( pList
->nExpr
==iFirst
+i
+1 );
2086 pList
->a
[pList
->nExpr
-1].zEName
= pColumns
->a
[i
].zName
;
2087 pColumns
->a
[i
].zName
= 0;
2091 if( !db
->mallocFailed
&& pExpr
->op
==TK_SELECT
&& ALWAYS(pList
!=0) ){
2092 Expr
*pFirst
= pList
->a
[iFirst
].pExpr
;
2093 assert( pFirst
!=0 );
2094 assert( pFirst
->op
==TK_SELECT_COLUMN
);
2096 /* Store the SELECT statement in pRight so it will be deleted when
2097 ** sqlite3ExprListDelete() is called */
2098 pFirst
->pRight
= pExpr
;
2101 /* Remember the size of the LHS in iTable so that we can check that
2102 ** the RHS and LHS sizes match during code generation. */
2103 pFirst
->iTable
= pColumns
->nId
;
2106 vector_append_error
:
2107 sqlite3ExprUnmapAndDelete(pParse
, pExpr
);
2108 sqlite3IdListDelete(db
, pColumns
);
2113 ** Set the sort order for the last element on the given ExprList.
2115 void sqlite3ExprListSetSortOrder(ExprList
*p
, int iSortOrder
, int eNulls
){
2116 struct ExprList_item
*pItem
;
2118 assert( p
->nExpr
>0 );
2120 assert( SQLITE_SO_UNDEFINED
<0 && SQLITE_SO_ASC
==0 && SQLITE_SO_DESC
>0 );
2121 assert( iSortOrder
==SQLITE_SO_UNDEFINED
2122 || iSortOrder
==SQLITE_SO_ASC
2123 || iSortOrder
==SQLITE_SO_DESC
2125 assert( eNulls
==SQLITE_SO_UNDEFINED
2126 || eNulls
==SQLITE_SO_ASC
2127 || eNulls
==SQLITE_SO_DESC
2130 pItem
= &p
->a
[p
->nExpr
-1];
2131 assert( pItem
->fg
.bNulls
==0 );
2132 if( iSortOrder
==SQLITE_SO_UNDEFINED
){
2133 iSortOrder
= SQLITE_SO_ASC
;
2135 pItem
->fg
.sortFlags
= (u8
)iSortOrder
;
2137 if( eNulls
!=SQLITE_SO_UNDEFINED
){
2138 pItem
->fg
.bNulls
= 1;
2139 if( iSortOrder
!=eNulls
){
2140 pItem
->fg
.sortFlags
|= KEYINFO_ORDER_BIGNULL
;
2146 ** Set the ExprList.a[].zEName element of the most recently added item
2147 ** on the expression list.
2149 ** pList might be NULL following an OOM error. But pName should never be
2150 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2153 void sqlite3ExprListSetName(
2154 Parse
*pParse
, /* Parsing context */
2155 ExprList
*pList
, /* List to which to add the span. */
2156 const Token
*pName
, /* Name to be added */
2157 int dequote
/* True to cause the name to be dequoted */
2159 assert( pList
!=0 || pParse
->db
->mallocFailed
!=0 );
2160 assert( pParse
->eParseMode
!=PARSE_MODE_UNMAP
|| dequote
==0 );
2162 struct ExprList_item
*pItem
;
2163 assert( pList
->nExpr
>0 );
2164 pItem
= &pList
->a
[pList
->nExpr
-1];
2165 assert( pItem
->zEName
==0 );
2166 assert( pItem
->fg
.eEName
==ENAME_NAME
);
2167 pItem
->zEName
= sqlite3DbStrNDup(pParse
->db
, pName
->z
, pName
->n
);
2169 /* If dequote==0, then pName->z does not point to part of a DDL
2170 ** statement handled by the parser. And so no token need be added
2171 ** to the token-map. */
2172 sqlite3Dequote(pItem
->zEName
);
2173 if( IN_RENAME_OBJECT
){
2174 sqlite3RenameTokenMap(pParse
, (const void*)pItem
->zEName
, pName
);
2181 ** Set the ExprList.a[].zSpan element of the most recently added item
2182 ** on the expression list.
2184 ** pList might be NULL following an OOM error. But pSpan should never be
2185 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2188 void sqlite3ExprListSetSpan(
2189 Parse
*pParse
, /* Parsing context */
2190 ExprList
*pList
, /* List to which to add the span. */
2191 const char *zStart
, /* Start of the span */
2192 const char *zEnd
/* End of the span */
2194 sqlite3
*db
= pParse
->db
;
2195 assert( pList
!=0 || db
->mallocFailed
!=0 );
2197 struct ExprList_item
*pItem
= &pList
->a
[pList
->nExpr
-1];
2198 assert( pList
->nExpr
>0 );
2199 if( pItem
->zEName
==0 ){
2200 pItem
->zEName
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
2201 pItem
->fg
.eEName
= ENAME_SPAN
;
2207 ** If the expression list pEList contains more than iLimit elements,
2208 ** leave an error message in pParse.
2210 void sqlite3ExprListCheckLength(
2215 int mx
= pParse
->db
->aLimit
[SQLITE_LIMIT_COLUMN
];
2216 testcase( pEList
&& pEList
->nExpr
==mx
);
2217 testcase( pEList
&& pEList
->nExpr
==mx
+1 );
2218 if( pEList
&& pEList
->nExpr
>mx
){
2219 sqlite3ErrorMsg(pParse
, "too many columns in %s", zObject
);
2224 ** Delete an entire expression list.
2226 static SQLITE_NOINLINE
void exprListDeleteNN(sqlite3
*db
, ExprList
*pList
){
2227 int i
= pList
->nExpr
;
2228 struct ExprList_item
*pItem
= pList
->a
;
2229 assert( pList
->nExpr
>0 );
2232 sqlite3ExprDelete(db
, pItem
->pExpr
);
2233 if( pItem
->zEName
) sqlite3DbNNFreeNN(db
, pItem
->zEName
);
2236 sqlite3DbNNFreeNN(db
, pList
);
2238 void sqlite3ExprListDelete(sqlite3
*db
, ExprList
*pList
){
2239 if( pList
) exprListDeleteNN(db
, pList
);
2241 void sqlite3ExprListDeleteGeneric(sqlite3
*db
, void *pList
){
2242 if( ALWAYS(pList
) ) exprListDeleteNN(db
, (ExprList
*)pList
);
2246 ** Return the bitwise-OR of all Expr.flags fields in the given
2249 u32
sqlite3ExprListFlags(const ExprList
*pList
){
2253 for(i
=0; i
<pList
->nExpr
; i
++){
2254 Expr
*pExpr
= pList
->a
[i
].pExpr
;
2262 ** This is a SELECT-node callback for the expression walker that
2263 ** always "fails". By "fail" in this case, we mean set
2264 ** pWalker->eCode to zero and abort.
2266 ** This callback is used by multiple expression walkers.
2268 int sqlite3SelectWalkFail(Walker
*pWalker
, Select
*NotUsed
){
2269 UNUSED_PARAMETER(NotUsed
);
2275 ** Check the input string to see if it is "true" or "false" (in any case).
2277 ** If the string is.... Return
2279 ** "false" EP_IsFalse
2282 u32
sqlite3IsTrueOrFalse(const char *zIn
){
2283 if( sqlite3StrICmp(zIn
, "true")==0 ) return EP_IsTrue
;
2284 if( sqlite3StrICmp(zIn
, "false")==0 ) return EP_IsFalse
;
2290 ** If the input expression is an ID with the name "true" or "false"
2291 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2292 ** the conversion happened, and zero if the expression is unaltered.
2294 int sqlite3ExprIdToTrueFalse(Expr
*pExpr
){
2296 assert( pExpr
->op
==TK_ID
|| pExpr
->op
==TK_STRING
);
2297 if( !ExprHasProperty(pExpr
, EP_Quoted
|EP_IntValue
)
2298 && (v
= sqlite3IsTrueOrFalse(pExpr
->u
.zToken
))!=0
2300 pExpr
->op
= TK_TRUEFALSE
;
2301 ExprSetProperty(pExpr
, v
);
2308 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2309 ** and 0 if it is FALSE.
2311 int sqlite3ExprTruthValue(const Expr
*pExpr
){
2312 pExpr
= sqlite3ExprSkipCollateAndLikely((Expr
*)pExpr
);
2313 assert( pExpr
->op
==TK_TRUEFALSE
);
2314 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2315 assert( sqlite3StrICmp(pExpr
->u
.zToken
,"true")==0
2316 || sqlite3StrICmp(pExpr
->u
.zToken
,"false")==0 );
2317 return pExpr
->u
.zToken
[4]==0;
2321 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2322 ** terms that are always true or false. Return the simplified expression.
2323 ** Or return the original expression if no simplification is possible.
2327 ** (x<10) AND true => (x<10)
2328 ** (x<10) AND false => false
2329 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2330 ** (x<10) AND (y=22 OR true) => (x<10)
2331 ** (y=22) OR true => true
2333 Expr
*sqlite3ExprSimplifiedAndOr(Expr
*pExpr
){
2335 if( pExpr
->op
==TK_AND
|| pExpr
->op
==TK_OR
){
2336 Expr
*pRight
= sqlite3ExprSimplifiedAndOr(pExpr
->pRight
);
2337 Expr
*pLeft
= sqlite3ExprSimplifiedAndOr(pExpr
->pLeft
);
2338 if( ExprAlwaysTrue(pLeft
) || ExprAlwaysFalse(pRight
) ){
2339 pExpr
= pExpr
->op
==TK_AND
? pRight
: pLeft
;
2340 }else if( ExprAlwaysTrue(pRight
) || ExprAlwaysFalse(pLeft
) ){
2341 pExpr
= pExpr
->op
==TK_AND
? pLeft
: pRight
;
2349 ** These routines are Walker callbacks used to check expressions to
2350 ** see if they are "constant" for some definition of constant. The
2351 ** Walker.eCode value determines the type of "constant" we are looking
2354 ** These callback routines are used to implement the following:
2356 ** sqlite3ExprIsConstant() pWalker->eCode==1
2357 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2358 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2359 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2361 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2362 ** is found to not be a constant.
2364 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2365 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2366 ** when parsing an existing schema out of the sqlite_schema table and 4
2367 ** when processing a new CREATE TABLE statement. A bound parameter raises
2368 ** an error for new statements, but is silently converted
2369 ** to NULL for existing schemas. This allows sqlite_schema tables that
2370 ** contain a bound parameter because they were generated by older versions
2371 ** of SQLite to be parsed by newer versions of SQLite without raising a
2372 ** malformed schema error.
2374 static int exprNodeIsConstant(Walker
*pWalker
, Expr
*pExpr
){
2376 /* If pWalker->eCode is 2 then any term of the expression that comes from
2377 ** the ON or USING clauses of an outer join disqualifies the expression
2378 ** from being considered constant. */
2379 if( pWalker
->eCode
==2 && ExprHasProperty(pExpr
, EP_OuterON
) ){
2384 switch( pExpr
->op
){
2385 /* Consider functions to be constant if all their arguments are constant
2386 ** and either pWalker->eCode==4 or 5 or the function has the
2387 ** SQLITE_FUNC_CONST flag. */
2389 if( (pWalker
->eCode
>=4 || ExprHasProperty(pExpr
,EP_ConstFunc
))
2390 && !ExprHasProperty(pExpr
, EP_WinFunc
)
2392 if( pWalker
->eCode
==5 ) ExprSetProperty(pExpr
, EP_FromDDL
);
2393 return WRC_Continue
;
2399 /* Convert "true" or "false" in a DEFAULT clause into the
2400 ** appropriate TK_TRUEFALSE operator */
2401 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
2404 /* no break */ deliberate_fall_through
2406 case TK_AGG_FUNCTION
:
2408 testcase( pExpr
->op
==TK_ID
);
2409 testcase( pExpr
->op
==TK_COLUMN
);
2410 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
2411 testcase( pExpr
->op
==TK_AGG_COLUMN
);
2412 if( ExprHasProperty(pExpr
, EP_FixedCol
) && pWalker
->eCode
!=2 ){
2413 return WRC_Continue
;
2415 if( pWalker
->eCode
==3 && pExpr
->iTable
==pWalker
->u
.iCur
){
2416 return WRC_Continue
;
2418 /* no break */ deliberate_fall_through
2419 case TK_IF_NULL_ROW
:
2422 testcase( pExpr
->op
==TK_REGISTER
);
2423 testcase( pExpr
->op
==TK_IF_NULL_ROW
);
2424 testcase( pExpr
->op
==TK_DOT
);
2428 if( pWalker
->eCode
==5 ){
2429 /* Silently convert bound parameters that appear inside of CREATE
2430 ** statements into a NULL when parsing the CREATE statement text out
2431 ** of the sqlite_schema table */
2432 pExpr
->op
= TK_NULL
;
2433 }else if( pWalker
->eCode
==4 ){
2434 /* A bound parameter in a CREATE statement that originates from
2435 ** sqlite3_prepare() causes an error */
2439 /* no break */ deliberate_fall_through
2441 testcase( pExpr
->op
==TK_SELECT
); /* sqlite3SelectWalkFail() disallows */
2442 testcase( pExpr
->op
==TK_EXISTS
); /* sqlite3SelectWalkFail() disallows */
2443 return WRC_Continue
;
2446 static int exprIsConst(Expr
*p
, int initFlag
, int iCur
){
2449 w
.xExprCallback
= exprNodeIsConstant
;
2450 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2452 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2455 sqlite3WalkExpr(&w
, p
);
2460 ** Walk an expression tree. Return non-zero if the expression is constant
2461 ** and 0 if it involves variables or function calls.
2463 ** For the purposes of this function, a double-quoted string (ex: "abc")
2464 ** is considered a variable but a single-quoted string (ex: 'abc') is
2467 int sqlite3ExprIsConstant(Expr
*p
){
2468 return exprIsConst(p
, 1, 0);
2472 ** Walk an expression tree. Return non-zero if
2474 ** (1) the expression is constant, and
2475 ** (2) the expression does originate in the ON or USING clause
2476 ** of a LEFT JOIN, and
2477 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2478 ** operands created by the constant propagation optimization.
2480 ** When this routine returns true, it indicates that the expression
2481 ** can be added to the pParse->pConstExpr list and evaluated once when
2482 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2484 int sqlite3ExprIsConstantNotJoin(Expr
*p
){
2485 return exprIsConst(p
, 2, 0);
2489 ** Walk an expression tree. Return non-zero if the expression is constant
2490 ** for any single row of the table with cursor iCur. In other words, the
2491 ** expression must not refer to any non-deterministic function nor any
2492 ** table other than iCur.
2494 int sqlite3ExprIsTableConstant(Expr
*p
, int iCur
){
2495 return exprIsConst(p
, 3, iCur
);
2499 ** Check pExpr to see if it is an constraint on the single data source
2500 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
2501 ** constrains pSrc but does not depend on any other tables or data
2502 ** sources anywhere else in the query. Return true (non-zero) if pExpr
2503 ** is a constraint on pSrc only.
2505 ** This is an optimization. False negatives will perhaps cause slower
2506 ** queries, but false positives will yield incorrect answers. So when in
2509 ** To be an single-source constraint, the following must be true:
2511 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2513 ** (2) pExpr cannot use subqueries or non-deterministic functions.
2515 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2516 ** (Is there some way to relax this constraint?)
2518 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2519 ** (4a) pExpr must come from an ON clause..
2520 ** (4b) and specifically the ON clause associated with the LEFT JOIN.
2522 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2523 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2524 ** clause, not an ON clause.
2528 ** (6a) pExpr does not originate in an ON or USING clause, or
2530 ** (6b) The ON or USING clause from which pExpr is derived is
2531 ** not to the left of a RIGHT JOIN (or FULL JOIN).
2533 ** Without this restriction, accepting pExpr as a single-table
2534 ** constraint might move the the ON/USING filter expression
2535 ** from the left side of a RIGHT JOIN over to the right side,
2536 ** which leads to incorrect answers. See also restriction (9)
2539 int sqlite3ExprIsSingleTableConstraint(
2540 Expr
*pExpr
, /* The constraint */
2541 const SrcList
*pSrcList
, /* Complete FROM clause */
2542 int iSrc
/* Which element of pSrcList to use */
2544 const SrcItem
*pSrc
= &pSrcList
->a
[iSrc
];
2545 if( pSrc
->fg
.jointype
& JT_LTORJ
){
2546 return 0; /* rule (3) */
2548 if( pSrc
->fg
.jointype
& JT_LEFT
){
2549 if( !ExprHasProperty(pExpr
, EP_OuterON
) ) return 0; /* rule (4a) */
2550 if( pExpr
->w
.iJoin
!=pSrc
->iCursor
) return 0; /* rule (4b) */
2552 if( ExprHasProperty(pExpr
, EP_OuterON
) ) return 0; /* rule (5) */
2554 if( ExprHasProperty(pExpr
, EP_OuterON
|EP_InnerON
) /* (6a) */
2555 && (pSrcList
->a
[0].fg
.jointype
& JT_LTORJ
)!=0 /* Fast pre-test of (6b) */
2558 for(jj
=0; jj
<iSrc
; jj
++){
2559 if( pExpr
->w
.iJoin
==pSrcList
->a
[jj
].iCursor
){
2560 if( (pSrcList
->a
[jj
].fg
.jointype
& JT_LTORJ
)!=0 ){
2561 return 0; /* restriction (6) */
2567 return sqlite3ExprIsTableConstant(pExpr
, pSrc
->iCursor
); /* rules (1), (2) */
2572 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2574 static int exprNodeIsConstantOrGroupBy(Walker
*pWalker
, Expr
*pExpr
){
2575 ExprList
*pGroupBy
= pWalker
->u
.pGroupBy
;
2578 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2580 for(i
=0; i
<pGroupBy
->nExpr
; i
++){
2581 Expr
*p
= pGroupBy
->a
[i
].pExpr
;
2582 if( sqlite3ExprCompare(0, pExpr
, p
, -1)<2 ){
2583 CollSeq
*pColl
= sqlite3ExprNNCollSeq(pWalker
->pParse
, p
);
2584 if( sqlite3IsBinary(pColl
) ){
2590 /* Check if pExpr is a sub-select. If so, consider it variable. */
2591 if( ExprUseXSelect(pExpr
) ){
2596 return exprNodeIsConstant(pWalker
, pExpr
);
2600 ** Walk the expression tree passed as the first argument. Return non-zero
2601 ** if the expression consists entirely of constants or copies of terms
2602 ** in pGroupBy that sort with the BINARY collation sequence.
2604 ** This routine is used to determine if a term of the HAVING clause can
2605 ** be promoted into the WHERE clause. In order for such a promotion to work,
2606 ** the value of the HAVING clause term must be the same for all members of
2607 ** a "group". The requirement that the GROUP BY term must be BINARY
2608 ** assumes that no other collating sequence will have a finer-grained
2609 ** grouping than binary. In other words (A=B COLLATE binary) implies
2610 ** A=B in every other collating sequence. The requirement that the
2611 ** GROUP BY be BINARY is stricter than necessary. It would also work
2612 ** to promote HAVING clauses that use the same alternative collating
2613 ** sequence as the GROUP BY term, but that is much harder to check,
2614 ** alternative collating sequences are uncommon, and this is only an
2615 ** optimization, so we take the easy way out and simply require the
2616 ** GROUP BY to use the BINARY collating sequence.
2618 int sqlite3ExprIsConstantOrGroupBy(Parse
*pParse
, Expr
*p
, ExprList
*pGroupBy
){
2621 w
.xExprCallback
= exprNodeIsConstantOrGroupBy
;
2622 w
.xSelectCallback
= 0;
2623 w
.u
.pGroupBy
= pGroupBy
;
2625 sqlite3WalkExpr(&w
, p
);
2630 ** Walk an expression tree for the DEFAULT field of a column definition
2631 ** in a CREATE TABLE statement. Return non-zero if the expression is
2632 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2633 ** the expression is constant or a function call with constant arguments.
2634 ** Return and 0 if there are any variables.
2636 ** isInit is true when parsing from sqlite_schema. isInit is false when
2637 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2638 ** (such as ? or $abc) in the expression are converted into NULL. When
2639 ** isInit is false, parameters raise an error. Parameters should not be
2640 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2641 ** allowed it, so we need to support it when reading sqlite_schema for
2642 ** backwards compatibility.
2644 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2646 ** For the purposes of this function, a double-quoted string (ex: "abc")
2647 ** is considered a variable but a single-quoted string (ex: 'abc') is
2650 int sqlite3ExprIsConstantOrFunction(Expr
*p
, u8 isInit
){
2651 assert( isInit
==0 || isInit
==1 );
2652 return exprIsConst(p
, 4+isInit
, 0);
2655 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2657 ** Walk an expression tree. Return 1 if the expression contains a
2658 ** subquery of some kind. Return 0 if there are no subqueries.
2660 int sqlite3ExprContainsSubquery(Expr
*p
){
2663 w
.xExprCallback
= sqlite3ExprWalkNoop
;
2664 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2666 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2668 sqlite3WalkExpr(&w
, p
);
2674 ** If the expression p codes a constant integer that is small enough
2675 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2676 ** in *pValue. If the expression is not an integer or if it is too big
2677 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2679 int sqlite3ExprIsInteger(const Expr
*p
, int *pValue
){
2681 if( NEVER(p
==0) ) return 0; /* Used to only happen following on OOM */
2683 /* If an expression is an integer literal that fits in a signed 32-bit
2684 ** integer, then the EP_IntValue flag will have already been set */
2685 assert( p
->op
!=TK_INTEGER
|| (p
->flags
& EP_IntValue
)!=0
2686 || sqlite3GetInt32(p
->u
.zToken
, &rc
)==0 );
2688 if( p
->flags
& EP_IntValue
){
2689 *pValue
= p
->u
.iValue
;
2694 rc
= sqlite3ExprIsInteger(p
->pLeft
, pValue
);
2699 if( sqlite3ExprIsInteger(p
->pLeft
, &v
) ){
2700 assert( ((unsigned int)v
)!=0x80000000 );
2712 ** Return FALSE if there is no chance that the expression can be NULL.
2714 ** If the expression might be NULL or if the expression is too complex
2715 ** to tell return TRUE.
2717 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2718 ** when we know that a value cannot be NULL. Hence, a false positive
2719 ** (returning TRUE when in fact the expression can never be NULL) might
2720 ** be a small performance hit but is otherwise harmless. On the other
2721 ** hand, a false negative (returning FALSE when the result could be NULL)
2722 ** will likely result in an incorrect answer. So when in doubt, return
2725 int sqlite3ExprCanBeNull(const Expr
*p
){
2728 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){
2733 if( op
==TK_REGISTER
) op
= p
->op2
;
2741 assert( ExprUseYTab(p
) );
2742 return ExprHasProperty(p
, EP_CanBeNull
) ||
2743 NEVER(p
->y
.pTab
==0) || /* Reference to column of index on expr */
2745 && p
->y
.pTab
->aCol
!=0 /* Possible due to prior error */
2746 && ALWAYS(p
->iColumn
<p
->y
.pTab
->nCol
)
2747 && p
->y
.pTab
->aCol
[p
->iColumn
].notNull
==0);
2754 ** Return TRUE if the given expression is a constant which would be
2755 ** unchanged by OP_Affinity with the affinity given in the second
2758 ** This routine is used to determine if the OP_Affinity operation
2759 ** can be omitted. When in doubt return FALSE. A false negative
2760 ** is harmless. A false positive, however, can result in the wrong
2763 int sqlite3ExprNeedsNoAffinityChange(const Expr
*p
, char aff
){
2766 if( aff
==SQLITE_AFF_BLOB
) return 1;
2767 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){
2768 if( p
->op
==TK_UMINUS
) unaryMinus
= 1;
2772 if( op
==TK_REGISTER
) op
= p
->op2
;
2775 return aff
>=SQLITE_AFF_NUMERIC
;
2778 return aff
>=SQLITE_AFF_NUMERIC
;
2781 return !unaryMinus
&& aff
==SQLITE_AFF_TEXT
;
2787 assert( p
->iTable
>=0 ); /* p cannot be part of a CHECK constraint */
2788 return aff
>=SQLITE_AFF_NUMERIC
&& p
->iColumn
<0;
2797 ** Return TRUE if the given string is a row-id column name.
2799 int sqlite3IsRowid(const char *z
){
2800 if( sqlite3StrICmp(z
, "_ROWID_")==0 ) return 1;
2801 if( sqlite3StrICmp(z
, "ROWID")==0 ) return 1;
2802 if( sqlite3StrICmp(z
, "OID")==0 ) return 1;
2807 ** Return a pointer to a buffer containing a usable rowid alias for table
2808 ** pTab. An alias is usable if there is not an explicit user-defined column
2809 ** of the same name.
2811 const char *sqlite3RowidAlias(Table
*pTab
){
2812 const char *azOpt
[] = {"_ROWID_", "ROWID", "OID"};
2814 assert( VisibleRowid(pTab
) );
2815 for(ii
=0; ii
<ArraySize(azOpt
); ii
++){
2817 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
2818 if( sqlite3_stricmp(azOpt
[ii
], pTab
->aCol
[iCol
].zCnName
)==0 ) break;
2820 if( iCol
==pTab
->nCol
){
2828 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2829 ** that can be simplified to a direct table access, then return
2830 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2831 ** or if the SELECT statement needs to be materialized into a transient
2832 ** table, then return NULL.
2834 #ifndef SQLITE_OMIT_SUBQUERY
2835 static Select
*isCandidateForInOpt(const Expr
*pX
){
2841 if( !ExprUseXSelect(pX
) ) return 0; /* Not a subquery */
2842 if( ExprHasProperty(pX
, EP_VarSelect
) ) return 0; /* Correlated subq */
2844 if( p
->pPrior
) return 0; /* Not a compound SELECT */
2845 if( p
->selFlags
& (SF_Distinct
|SF_Aggregate
) ){
2846 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Distinct
);
2847 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Aggregate
);
2848 return 0; /* No DISTINCT keyword and no aggregate functions */
2850 assert( p
->pGroupBy
==0 ); /* Has no GROUP BY clause */
2851 if( p
->pLimit
) return 0; /* Has no LIMIT clause */
2852 if( p
->pWhere
) return 0; /* Has no WHERE clause */
2855 if( pSrc
->nSrc
!=1 ) return 0; /* Single term in FROM clause */
2856 if( pSrc
->a
[0].pSelect
) return 0; /* FROM is not a subquery or view */
2857 pTab
= pSrc
->a
[0].pTab
;
2859 assert( !IsView(pTab
) ); /* FROM clause is not a view */
2860 if( IsVirtual(pTab
) ) return 0; /* FROM clause not a virtual table */
2862 assert( pEList
!=0 );
2863 /* All SELECT results must be columns. */
2864 for(i
=0; i
<pEList
->nExpr
; i
++){
2865 Expr
*pRes
= pEList
->a
[i
].pExpr
;
2866 if( pRes
->op
!=TK_COLUMN
) return 0;
2867 assert( pRes
->iTable
==pSrc
->a
[0].iCursor
); /* Not a correlated subquery */
2871 #endif /* SQLITE_OMIT_SUBQUERY */
2873 #ifndef SQLITE_OMIT_SUBQUERY
2875 ** Generate code that checks the left-most column of index table iCur to see if
2876 ** it contains any NULL entries. Cause the register at regHasNull to be set
2877 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2878 ** to be set to NULL if iCur contains one or more NULL values.
2880 static void sqlite3SetHasNullFlag(Vdbe
*v
, int iCur
, int regHasNull
){
2882 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regHasNull
);
2883 addr1
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iCur
); VdbeCoverage(v
);
2884 sqlite3VdbeAddOp3(v
, OP_Column
, iCur
, 0, regHasNull
);
2885 sqlite3VdbeChangeP5(v
, OPFLAG_TYPEOFARG
);
2886 VdbeComment((v
, "first_entry_in(%d)", iCur
));
2887 sqlite3VdbeJumpHere(v
, addr1
);
2892 #ifndef SQLITE_OMIT_SUBQUERY
2894 ** The argument is an IN operator with a list (not a subquery) on the
2895 ** right-hand side. Return TRUE if that list is constant.
2897 static int sqlite3InRhsIsConstant(Expr
*pIn
){
2900 assert( !ExprHasProperty(pIn
, EP_xIsSelect
) );
2903 res
= sqlite3ExprIsConstant(pIn
);
2910 ** This function is used by the implementation of the IN (...) operator.
2911 ** The pX parameter is the expression on the RHS of the IN operator, which
2912 ** might be either a list of expressions or a subquery.
2914 ** The job of this routine is to find or create a b-tree object that can
2915 ** be used either to test for membership in the RHS set or to iterate through
2916 ** all members of the RHS set, skipping duplicates.
2918 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2919 ** and the *piTab parameter is set to the index of that cursor.
2921 ** The returned value of this function indicates the b-tree type, as follows:
2923 ** IN_INDEX_ROWID - The cursor was opened on a database table.
2924 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2925 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2926 ** IN_INDEX_EPH - The cursor was opened on a specially created and
2927 ** populated ephemeral table.
2928 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2929 ** implemented as a sequence of comparisons.
2931 ** An existing b-tree might be used if the RHS expression pX is a simple
2932 ** subquery such as:
2934 ** SELECT <column1>, <column2>... FROM <table>
2936 ** If the RHS of the IN operator is a list or a more complex subquery, then
2937 ** an ephemeral table might need to be generated from the RHS and then
2938 ** pX->iTable made to point to the ephemeral table instead of an
2939 ** existing table. In this case, the creation and initialization of the
2940 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag
2941 ** will be set on pX and the pX->y.sub fields will be set to show where
2942 ** the subroutine is coded.
2944 ** The inFlags parameter must contain, at a minimum, one of the bits
2945 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2946 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2947 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2948 ** be used to loop over all values of the RHS of the IN operator.
2950 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2951 ** through the set members) then the b-tree must not contain duplicates.
2952 ** An ephemeral table will be created unless the selected columns are guaranteed
2953 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2954 ** a UNIQUE constraint or index.
2956 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2957 ** for fast set membership tests) then an ephemeral table must
2958 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2959 ** index can be found with the specified <columns> as its left-most.
2961 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2962 ** if the RHS of the IN operator is a list (not a subquery) then this
2963 ** routine might decide that creating an ephemeral b-tree for membership
2964 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2965 ** calling routine should implement the IN operator using a sequence
2966 ** of Eq or Ne comparison operations.
2968 ** When the b-tree is being used for membership tests, the calling function
2969 ** might need to know whether or not the RHS side of the IN operator
2970 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
2971 ** if there is any chance that the (...) might contain a NULL value at
2972 ** runtime, then a register is allocated and the register number written
2973 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2974 ** NULL value, then *prRhsHasNull is left unchanged.
2976 ** If a register is allocated and its location stored in *prRhsHasNull, then
2977 ** the value in that register will be NULL if the b-tree contains one or more
2978 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2981 ** If the aiMap parameter is not NULL, it must point to an array containing
2982 ** one element for each column returned by the SELECT statement on the RHS
2983 ** of the IN(...) operator. The i'th entry of the array is populated with the
2984 ** offset of the index column that matches the i'th column returned by the
2985 ** SELECT. For example, if the expression and selected index are:
2987 ** (?,?,?) IN (SELECT a, b, c FROM t1)
2988 ** CREATE INDEX i1 ON t1(b, c, a);
2990 ** then aiMap[] is populated with {2, 0, 1}.
2992 #ifndef SQLITE_OMIT_SUBQUERY
2993 int sqlite3FindInIndex(
2994 Parse
*pParse
, /* Parsing context */
2995 Expr
*pX
, /* The IN expression */
2996 u32 inFlags
, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2997 int *prRhsHasNull
, /* Register holding NULL status. See notes */
2998 int *aiMap
, /* Mapping from Index fields to RHS fields */
2999 int *piTab
/* OUT: index to use */
3001 Select
*p
; /* SELECT to the right of IN operator */
3002 int eType
= 0; /* Type of RHS table. IN_INDEX_* */
3003 int iTab
; /* Cursor of the RHS table */
3004 int mustBeUnique
; /* True if RHS must be unique */
3005 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Virtual machine being coded */
3007 assert( pX
->op
==TK_IN
);
3008 mustBeUnique
= (inFlags
& IN_INDEX_LOOP
)!=0;
3009 iTab
= pParse
->nTab
++;
3011 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
3012 ** whether or not the SELECT result contains NULL values, check whether
3013 ** or not NULL is actually possible (it may not be, for example, due
3014 ** to NOT NULL constraints in the schema). If no NULL values are possible,
3015 ** set prRhsHasNull to 0 before continuing. */
3016 if( prRhsHasNull
&& ExprUseXSelect(pX
) ){
3018 ExprList
*pEList
= pX
->x
.pSelect
->pEList
;
3019 for(i
=0; i
<pEList
->nExpr
; i
++){
3020 if( sqlite3ExprCanBeNull(pEList
->a
[i
].pExpr
) ) break;
3022 if( i
==pEList
->nExpr
){
3027 /* Check to see if an existing table or index can be used to
3028 ** satisfy the query. This is preferable to generating a new
3029 ** ephemeral table. */
3030 if( pParse
->nErr
==0 && (p
= isCandidateForInOpt(pX
))!=0 ){
3031 sqlite3
*db
= pParse
->db
; /* Database connection */
3032 Table
*pTab
; /* Table <table>. */
3033 int iDb
; /* Database idx for pTab */
3034 ExprList
*pEList
= p
->pEList
;
3035 int nExpr
= pEList
->nExpr
;
3037 assert( p
->pEList
!=0 ); /* Because of isCandidateForInOpt(p) */
3038 assert( p
->pEList
->a
[0].pExpr
!=0 ); /* Because of isCandidateForInOpt(p) */
3039 assert( p
->pSrc
!=0 ); /* Because of isCandidateForInOpt(p) */
3040 pTab
= p
->pSrc
->a
[0].pTab
;
3042 /* Code an OP_Transaction and OP_TableLock for <table>. */
3043 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
3044 assert( iDb
>=0 && iDb
<SQLITE_MAX_DB
);
3045 sqlite3CodeVerifySchema(pParse
, iDb
);
3046 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 0, pTab
->zName
);
3048 assert(v
); /* sqlite3GetVdbe() has always been previously called */
3049 if( nExpr
==1 && pEList
->a
[0].pExpr
->iColumn
<0 ){
3050 /* The "x IN (SELECT rowid FROM table)" case */
3051 int iAddr
= sqlite3VdbeAddOp0(v
, OP_Once
);
3054 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
3055 eType
= IN_INDEX_ROWID
;
3056 ExplainQueryPlan((pParse
, 0,
3057 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab
->zName
));
3058 sqlite3VdbeJumpHere(v
, iAddr
);
3060 Index
*pIdx
; /* Iterator variable */
3061 int affinity_ok
= 1;
3064 /* Check that the affinity that will be used to perform each
3065 ** comparison is the same as the affinity of each column in table
3066 ** on the RHS of the IN operator. If it not, it is not possible to
3067 ** use any index of the RHS table. */
3068 for(i
=0; i
<nExpr
&& affinity_ok
; i
++){
3069 Expr
*pLhs
= sqlite3VectorFieldSubexpr(pX
->pLeft
, i
);
3070 int iCol
= pEList
->a
[i
].pExpr
->iColumn
;
3071 char idxaff
= sqlite3TableColumnAffinity(pTab
,iCol
); /* RHS table */
3072 char cmpaff
= sqlite3CompareAffinity(pLhs
, idxaff
);
3073 testcase( cmpaff
==SQLITE_AFF_BLOB
);
3074 testcase( cmpaff
==SQLITE_AFF_TEXT
);
3076 case SQLITE_AFF_BLOB
:
3078 case SQLITE_AFF_TEXT
:
3079 /* sqlite3CompareAffinity() only returns TEXT if one side or the
3080 ** other has no affinity and the other side is TEXT. Hence,
3081 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
3082 ** and for the term on the LHS of the IN to have no affinity. */
3083 assert( idxaff
==SQLITE_AFF_TEXT
);
3086 affinity_ok
= sqlite3IsNumericAffinity(idxaff
);
3091 /* Search for an existing index that will work for this IN operator */
3092 for(pIdx
=pTab
->pIndex
; pIdx
&& eType
==0; pIdx
=pIdx
->pNext
){
3093 Bitmask colUsed
; /* Columns of the index used */
3094 Bitmask mCol
; /* Mask for the current column */
3095 if( pIdx
->nColumn
<nExpr
) continue;
3096 if( pIdx
->pPartIdxWhere
!=0 ) continue;
3097 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
3098 ** BITMASK(nExpr) without overflowing */
3099 testcase( pIdx
->nColumn
==BMS
-2 );
3100 testcase( pIdx
->nColumn
==BMS
-1 );
3101 if( pIdx
->nColumn
>=BMS
-1 ) continue;
3103 if( pIdx
->nKeyCol
>nExpr
3104 ||(pIdx
->nColumn
>nExpr
&& !IsUniqueIndex(pIdx
))
3106 continue; /* This index is not unique over the IN RHS columns */
3110 colUsed
= 0; /* Columns of index used so far */
3111 for(i
=0; i
<nExpr
; i
++){
3112 Expr
*pLhs
= sqlite3VectorFieldSubexpr(pX
->pLeft
, i
);
3113 Expr
*pRhs
= pEList
->a
[i
].pExpr
;
3114 CollSeq
*pReq
= sqlite3BinaryCompareCollSeq(pParse
, pLhs
, pRhs
);
3117 for(j
=0; j
<nExpr
; j
++){
3118 if( pIdx
->aiColumn
[j
]!=pRhs
->iColumn
) continue;
3119 assert( pIdx
->azColl
[j
] );
3120 if( pReq
!=0 && sqlite3StrICmp(pReq
->zName
, pIdx
->azColl
[j
])!=0 ){
3125 if( j
==nExpr
) break;
3127 if( mCol
& colUsed
) break; /* Each column used only once */
3129 if( aiMap
) aiMap
[i
] = j
;
3132 assert( i
==nExpr
|| colUsed
!=(MASKBIT(nExpr
)-1) );
3133 if( colUsed
==(MASKBIT(nExpr
)-1) ){
3134 /* If we reach this point, that means the index pIdx is usable */
3135 int iAddr
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3136 ExplainQueryPlan((pParse
, 0,
3137 "USING INDEX %s FOR IN-OPERATOR",pIdx
->zName
));
3138 sqlite3VdbeAddOp3(v
, OP_OpenRead
, iTab
, pIdx
->tnum
, iDb
);
3139 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
3140 VdbeComment((v
, "%s", pIdx
->zName
));
3141 assert( IN_INDEX_INDEX_DESC
== IN_INDEX_INDEX_ASC
+1 );
3142 eType
= IN_INDEX_INDEX_ASC
+ pIdx
->aSortOrder
[0];
3145 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3146 i64 mask
= (1<<nExpr
)-1;
3147 sqlite3VdbeAddOp4Dup8(v
, OP_ColumnsUsed
,
3148 iTab
, 0, 0, (u8
*)&mask
, P4_INT64
);
3150 *prRhsHasNull
= ++pParse
->nMem
;
3152 sqlite3SetHasNullFlag(v
, iTab
, *prRhsHasNull
);
3155 sqlite3VdbeJumpHere(v
, iAddr
);
3157 } /* End loop over indexes */
3158 } /* End if( affinity_ok ) */
3159 } /* End if not an rowid index */
3160 } /* End attempt to optimize using an index */
3162 /* If no preexisting index is available for the IN clause
3163 ** and IN_INDEX_NOOP is an allowed reply
3164 ** and the RHS of the IN operator is a list, not a subquery
3165 ** and the RHS is not constant or has two or fewer terms,
3166 ** then it is not worth creating an ephemeral table to evaluate
3167 ** the IN operator so return IN_INDEX_NOOP.
3170 && (inFlags
& IN_INDEX_NOOP_OK
)
3172 && (!sqlite3InRhsIsConstant(pX
) || pX
->x
.pList
->nExpr
<=2)
3174 pParse
->nTab
--; /* Back out the allocation of the unused cursor */
3175 iTab
= -1; /* Cursor is not allocated */
3176 eType
= IN_INDEX_NOOP
;
3180 /* Could not find an existing table or index to use as the RHS b-tree.
3181 ** We will have to generate an ephemeral table to do the job.
3183 u32 savedNQueryLoop
= pParse
->nQueryLoop
;
3184 int rMayHaveNull
= 0;
3185 eType
= IN_INDEX_EPH
;
3186 if( inFlags
& IN_INDEX_LOOP
){
3187 pParse
->nQueryLoop
= 0;
3188 }else if( prRhsHasNull
){
3189 *prRhsHasNull
= rMayHaveNull
= ++pParse
->nMem
;
3191 assert( pX
->op
==TK_IN
);
3192 sqlite3CodeRhsOfIN(pParse
, pX
, iTab
);
3194 sqlite3SetHasNullFlag(v
, iTab
, rMayHaveNull
);
3196 pParse
->nQueryLoop
= savedNQueryLoop
;
3199 if( aiMap
&& eType
!=IN_INDEX_INDEX_ASC
&& eType
!=IN_INDEX_INDEX_DESC
){
3201 n
= sqlite3ExprVectorSize(pX
->pLeft
);
3202 for(i
=0; i
<n
; i
++) aiMap
[i
] = i
;
3209 #ifndef SQLITE_OMIT_SUBQUERY
3211 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3212 ** function allocates and returns a nul-terminated string containing
3213 ** the affinities to be used for each column of the comparison.
3215 ** It is the responsibility of the caller to ensure that the returned
3216 ** string is eventually freed using sqlite3DbFree().
3218 static char *exprINAffinity(Parse
*pParse
, const Expr
*pExpr
){
3219 Expr
*pLeft
= pExpr
->pLeft
;
3220 int nVal
= sqlite3ExprVectorSize(pLeft
);
3221 Select
*pSelect
= ExprUseXSelect(pExpr
) ? pExpr
->x
.pSelect
: 0;
3224 assert( pExpr
->op
==TK_IN
);
3225 zRet
= sqlite3DbMallocRaw(pParse
->db
, nVal
+1);
3228 for(i
=0; i
<nVal
; i
++){
3229 Expr
*pA
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3230 char a
= sqlite3ExprAffinity(pA
);
3232 zRet
[i
] = sqlite3CompareAffinity(pSelect
->pEList
->a
[i
].pExpr
, a
);
3243 #ifndef SQLITE_OMIT_SUBQUERY
3245 ** Load the Parse object passed as the first argument with an error
3246 ** message of the form:
3248 ** "sub-select returns N columns - expected M"
3250 void sqlite3SubselectError(Parse
*pParse
, int nActual
, int nExpect
){
3251 if( pParse
->nErr
==0 ){
3252 const char *zFmt
= "sub-select returns %d columns - expected %d";
3253 sqlite3ErrorMsg(pParse
, zFmt
, nActual
, nExpect
);
3259 ** Expression pExpr is a vector that has been used in a context where
3260 ** it is not permitted. If pExpr is a sub-select vector, this routine
3261 ** loads the Parse object with a message of the form:
3263 ** "sub-select returns N columns - expected 1"
3265 ** Or, if it is a regular scalar vector:
3267 ** "row value misused"
3269 void sqlite3VectorErrorMsg(Parse
*pParse
, Expr
*pExpr
){
3270 #ifndef SQLITE_OMIT_SUBQUERY
3271 if( ExprUseXSelect(pExpr
) ){
3272 sqlite3SubselectError(pParse
, pExpr
->x
.pSelect
->pEList
->nExpr
, 1);
3276 sqlite3ErrorMsg(pParse
, "row value misused");
3280 #ifndef SQLITE_OMIT_SUBQUERY
3282 ** Generate code that will construct an ephemeral table containing all terms
3283 ** in the RHS of an IN operator. The IN operator can be in either of two
3286 ** x IN (4,5,11) -- IN operator with list on right-hand side
3287 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3289 ** The pExpr parameter is the IN operator. The cursor number for the
3290 ** constructed ephemeral table is returned. The first time the ephemeral
3291 ** table is computed, the cursor number is also stored in pExpr->iTable,
3292 ** however the cursor number returned might not be the same, as it might
3293 ** have been duplicated using OP_OpenDup.
3295 ** If the LHS expression ("x" in the examples) is a column value, or
3296 ** the SELECT statement returns a column value, then the affinity of that
3297 ** column is used to build the index keys. If both 'x' and the
3298 ** SELECT... statement are columns, then numeric affinity is used
3299 ** if either column has NUMERIC or INTEGER affinity. If neither
3300 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3303 void sqlite3CodeRhsOfIN(
3304 Parse
*pParse
, /* Parsing context */
3305 Expr
*pExpr
, /* The IN operator */
3306 int iTab
/* Use this cursor number */
3308 int addrOnce
= 0; /* Address of the OP_Once instruction at top */
3309 int addr
; /* Address of OP_OpenEphemeral instruction */
3310 Expr
*pLeft
; /* the LHS of the IN operator */
3311 KeyInfo
*pKeyInfo
= 0; /* Key information */
3312 int nVal
; /* Size of vector pLeft */
3313 Vdbe
*v
; /* The prepared statement under construction */
3318 /* The evaluation of the IN must be repeated every time it
3319 ** is encountered if any of the following is true:
3321 ** * The right-hand side is a correlated subquery
3322 ** * The right-hand side is an expression list containing variables
3323 ** * We are inside a trigger
3325 ** If all of the above are false, then we can compute the RHS just once
3326 ** and reuse it many names.
3328 if( !ExprHasProperty(pExpr
, EP_VarSelect
) && pParse
->iSelfTab
==0 ){
3329 /* Reuse of the RHS is allowed */
3330 /* If this routine has already been coded, but the previous code
3331 ** might not have been invoked yet, so invoke it now as a subroutine.
3333 if( ExprHasProperty(pExpr
, EP_Subrtn
) ){
3334 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3335 if( ExprUseXSelect(pExpr
) ){
3336 ExplainQueryPlan((pParse
, 0, "REUSE LIST SUBQUERY %d",
3337 pExpr
->x
.pSelect
->selId
));
3339 assert( ExprUseYSub(pExpr
) );
3340 sqlite3VdbeAddOp2(v
, OP_Gosub
, pExpr
->y
.sub
.regReturn
,
3341 pExpr
->y
.sub
.iAddr
);
3342 assert( iTab
!=pExpr
->iTable
);
3343 sqlite3VdbeAddOp2(v
, OP_OpenDup
, iTab
, pExpr
->iTable
);
3344 sqlite3VdbeJumpHere(v
, addrOnce
);
3348 /* Begin coding the subroutine */
3349 assert( !ExprUseYWin(pExpr
) );
3350 ExprSetProperty(pExpr
, EP_Subrtn
);
3351 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
3352 pExpr
->y
.sub
.regReturn
= ++pParse
->nMem
;
3353 pExpr
->y
.sub
.iAddr
=
3354 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pExpr
->y
.sub
.regReturn
) + 1;
3356 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3359 /* Check to see if this is a vector IN operator */
3360 pLeft
= pExpr
->pLeft
;
3361 nVal
= sqlite3ExprVectorSize(pLeft
);
3363 /* Construct the ephemeral table that will contain the content of
3364 ** RHS of the IN operator.
3366 pExpr
->iTable
= iTab
;
3367 addr
= sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pExpr
->iTable
, nVal
);
3368 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3369 if( ExprUseXSelect(pExpr
) ){
3370 VdbeComment((v
, "Result of SELECT %u", pExpr
->x
.pSelect
->selId
));
3372 VdbeComment((v
, "RHS of IN operator"));
3375 pKeyInfo
= sqlite3KeyInfoAlloc(pParse
->db
, nVal
, 1);
3377 if( ExprUseXSelect(pExpr
) ){
3378 /* Case 1: expr IN (SELECT ...)
3380 ** Generate code to write the results of the select into the temporary
3381 ** table allocated and opened above.
3383 Select
*pSelect
= pExpr
->x
.pSelect
;
3384 ExprList
*pEList
= pSelect
->pEList
;
3386 ExplainQueryPlan((pParse
, 1, "%sLIST SUBQUERY %d",
3387 addrOnce
?"":"CORRELATED ", pSelect
->selId
3389 /* If the LHS and RHS of the IN operator do not match, that
3390 ** error will have been caught long before we reach this point. */
3391 if( ALWAYS(pEList
->nExpr
==nVal
) ){
3396 sqlite3SelectDestInit(&dest
, SRT_Set
, iTab
);
3397 dest
.zAffSdst
= exprINAffinity(pParse
, pExpr
);
3398 pSelect
->iLimit
= 0;
3399 testcase( pSelect
->selFlags
& SF_Distinct
);
3400 testcase( pKeyInfo
==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3401 pCopy
= sqlite3SelectDup(pParse
->db
, pSelect
, 0);
3402 rc
= pParse
->db
->mallocFailed
? 1 :sqlite3Select(pParse
, pCopy
, &dest
);
3403 sqlite3SelectDelete(pParse
->db
, pCopy
);
3404 sqlite3DbFree(pParse
->db
, dest
.zAffSdst
);
3406 sqlite3KeyInfoUnref(pKeyInfo
);
3409 assert( pKeyInfo
!=0 ); /* OOM will cause exit after sqlite3Select() */
3410 assert( pEList
!=0 );
3411 assert( pEList
->nExpr
>0 );
3412 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
3413 for(i
=0; i
<nVal
; i
++){
3414 Expr
*p
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3415 pKeyInfo
->aColl
[i
] = sqlite3BinaryCompareCollSeq(
3416 pParse
, p
, pEList
->a
[i
].pExpr
3420 }else if( ALWAYS(pExpr
->x
.pList
!=0) ){
3421 /* Case 2: expr IN (exprlist)
3423 ** For each expression, build an index key from the evaluation and
3424 ** store it in the temporary table. If <expr> is a column, then use
3425 ** that columns affinity when building index keys. If <expr> is not
3426 ** a column, use numeric affinity.
3428 char affinity
; /* Affinity of the LHS of the IN */
3430 ExprList
*pList
= pExpr
->x
.pList
;
3431 struct ExprList_item
*pItem
;
3433 affinity
= sqlite3ExprAffinity(pLeft
);
3434 if( affinity
<=SQLITE_AFF_NONE
){
3435 affinity
= SQLITE_AFF_BLOB
;
3436 }else if( affinity
==SQLITE_AFF_REAL
){
3437 affinity
= SQLITE_AFF_NUMERIC
;
3440 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
3441 pKeyInfo
->aColl
[0] = sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
3444 /* Loop through each expression in <exprlist>. */
3445 r1
= sqlite3GetTempReg(pParse
);
3446 r2
= sqlite3GetTempReg(pParse
);
3447 for(i
=pList
->nExpr
, pItem
=pList
->a
; i
>0; i
--, pItem
++){
3448 Expr
*pE2
= pItem
->pExpr
;
3450 /* If the expression is not constant then we will need to
3451 ** disable the test that was generated above that makes sure
3452 ** this code only executes once. Because for a non-constant
3453 ** expression we need to rerun this code each time.
3455 if( addrOnce
&& !sqlite3ExprIsConstant(pE2
) ){
3456 sqlite3VdbeChangeToNoop(v
, addrOnce
-1);
3457 sqlite3VdbeChangeToNoop(v
, addrOnce
);
3458 ExprClearProperty(pExpr
, EP_Subrtn
);
3462 /* Evaluate the expression and insert it into the temp table */
3463 sqlite3ExprCode(pParse
, pE2
, r1
);
3464 sqlite3VdbeAddOp4(v
, OP_MakeRecord
, r1
, 1, r2
, &affinity
, 1);
3465 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, iTab
, r2
, r1
, 1);
3467 sqlite3ReleaseTempReg(pParse
, r1
);
3468 sqlite3ReleaseTempReg(pParse
, r2
);
3471 sqlite3VdbeChangeP4(v
, addr
, (void *)pKeyInfo
, P4_KEYINFO
);
3474 sqlite3VdbeAddOp1(v
, OP_NullRow
, iTab
);
3475 sqlite3VdbeJumpHere(v
, addrOnce
);
3476 /* Subroutine return */
3477 assert( ExprUseYSub(pExpr
) );
3478 assert( sqlite3VdbeGetOp(v
,pExpr
->y
.sub
.iAddr
-1)->opcode
==OP_BeginSubrtn
3480 sqlite3VdbeAddOp3(v
, OP_Return
, pExpr
->y
.sub
.regReturn
,
3481 pExpr
->y
.sub
.iAddr
, 1);
3483 sqlite3ClearTempRegCache(pParse
);
3486 #endif /* SQLITE_OMIT_SUBQUERY */
3489 ** Generate code for scalar subqueries used as a subquery expression
3490 ** or EXISTS operator:
3492 ** (SELECT a FROM b) -- subquery
3493 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3495 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3497 ** Return the register that holds the result. For a multi-column SELECT,
3498 ** the result is stored in a contiguous array of registers and the
3499 ** return value is the register of the left-most result column.
3500 ** Return 0 if an error occurs.
3502 #ifndef SQLITE_OMIT_SUBQUERY
3503 int sqlite3CodeSubselect(Parse
*pParse
, Expr
*pExpr
){
3504 int addrOnce
= 0; /* Address of OP_Once at top of subroutine */
3505 int rReg
= 0; /* Register storing resulting */
3506 Select
*pSel
; /* SELECT statement to encode */
3507 SelectDest dest
; /* How to deal with SELECT result */
3508 int nReg
; /* Registers to allocate */
3509 Expr
*pLimit
; /* New limit expression */
3510 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3511 int addrExplain
; /* Address of OP_Explain instruction */
3514 Vdbe
*v
= pParse
->pVdbe
;
3516 if( pParse
->nErr
) return 0;
3517 testcase( pExpr
->op
==TK_EXISTS
);
3518 testcase( pExpr
->op
==TK_SELECT
);
3519 assert( pExpr
->op
==TK_EXISTS
|| pExpr
->op
==TK_SELECT
);
3520 assert( ExprUseXSelect(pExpr
) );
3521 pSel
= pExpr
->x
.pSelect
;
3523 /* If this routine has already been coded, then invoke it as a
3525 if( ExprHasProperty(pExpr
, EP_Subrtn
) ){
3526 ExplainQueryPlan((pParse
, 0, "REUSE SUBQUERY %d", pSel
->selId
));
3527 assert( ExprUseYSub(pExpr
) );
3528 sqlite3VdbeAddOp2(v
, OP_Gosub
, pExpr
->y
.sub
.regReturn
,
3529 pExpr
->y
.sub
.iAddr
);
3530 return pExpr
->iTable
;
3533 /* Begin coding the subroutine */
3534 assert( !ExprUseYWin(pExpr
) );
3535 assert( !ExprHasProperty(pExpr
, EP_Reduced
|EP_TokenOnly
) );
3536 ExprSetProperty(pExpr
, EP_Subrtn
);
3537 pExpr
->y
.sub
.regReturn
= ++pParse
->nMem
;
3538 pExpr
->y
.sub
.iAddr
=
3539 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pExpr
->y
.sub
.regReturn
) + 1;
3541 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3542 ** is encountered if any of the following is true:
3544 ** * The right-hand side is a correlated subquery
3545 ** * The right-hand side is an expression list containing variables
3546 ** * We are inside a trigger
3548 ** If all of the above are false, then we can run this code just once
3549 ** save the results, and reuse the same result on subsequent invocations.
3551 if( !ExprHasProperty(pExpr
, EP_VarSelect
) ){
3552 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3555 /* For a SELECT, generate code to put the values for all columns of
3556 ** the first row into an array of registers and return the index of
3557 ** the first register.
3559 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3560 ** into a register and return that register number.
3562 ** In both cases, the query is augmented with "LIMIT 1". Any
3563 ** preexisting limit is discarded in place of the new LIMIT 1.
3565 ExplainQueryPlan2(addrExplain
, (pParse
, 1, "%sSCALAR SUBQUERY %d",
3566 addrOnce
?"":"CORRELATED ", pSel
->selId
));
3567 sqlite3VdbeScanStatusCounters(v
, addrExplain
, addrExplain
, -1);
3568 nReg
= pExpr
->op
==TK_SELECT
? pSel
->pEList
->nExpr
: 1;
3569 sqlite3SelectDestInit(&dest
, 0, pParse
->nMem
+1);
3570 pParse
->nMem
+= nReg
;
3571 if( pExpr
->op
==TK_SELECT
){
3572 dest
.eDest
= SRT_Mem
;
3573 dest
.iSdst
= dest
.iSDParm
;
3575 sqlite3VdbeAddOp3(v
, OP_Null
, 0, dest
.iSDParm
, dest
.iSDParm
+nReg
-1);
3576 VdbeComment((v
, "Init subquery result"));
3578 dest
.eDest
= SRT_Exists
;
3579 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
.iSDParm
);
3580 VdbeComment((v
, "Init EXISTS result"));
3583 /* The subquery already has a limit. If the pre-existing limit is X
3584 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3585 sqlite3
*db
= pParse
->db
;
3586 pLimit
= sqlite3Expr(db
, TK_INTEGER
, "0");
3588 pLimit
->affExpr
= SQLITE_AFF_NUMERIC
;
3589 pLimit
= sqlite3PExpr(pParse
, TK_NE
,
3590 sqlite3ExprDup(db
, pSel
->pLimit
->pLeft
, 0), pLimit
);
3592 sqlite3ExprDeferredDelete(pParse
, pSel
->pLimit
->pLeft
);
3593 pSel
->pLimit
->pLeft
= pLimit
;
3595 /* If there is no pre-existing limit add a limit of 1 */
3596 pLimit
= sqlite3Expr(pParse
->db
, TK_INTEGER
, "1");
3597 pSel
->pLimit
= sqlite3PExpr(pParse
, TK_LIMIT
, pLimit
, 0);
3600 if( sqlite3Select(pParse
, pSel
, &dest
) ){
3601 pExpr
->op2
= pExpr
->op
;
3602 pExpr
->op
= TK_ERROR
;
3605 pExpr
->iTable
= rReg
= dest
.iSDParm
;
3606 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
3608 sqlite3VdbeJumpHere(v
, addrOnce
);
3610 sqlite3VdbeScanStatusRange(v
, addrExplain
, addrExplain
, -1);
3612 /* Subroutine return */
3613 assert( ExprUseYSub(pExpr
) );
3614 assert( sqlite3VdbeGetOp(v
,pExpr
->y
.sub
.iAddr
-1)->opcode
==OP_BeginSubrtn
3616 sqlite3VdbeAddOp3(v
, OP_Return
, pExpr
->y
.sub
.regReturn
,
3617 pExpr
->y
.sub
.iAddr
, 1);
3619 sqlite3ClearTempRegCache(pParse
);
3622 #endif /* SQLITE_OMIT_SUBQUERY */
3624 #ifndef SQLITE_OMIT_SUBQUERY
3626 ** Expr pIn is an IN(...) expression. This function checks that the
3627 ** sub-select on the RHS of the IN() operator has the same number of
3628 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3629 ** a sub-query, that the LHS is a vector of size 1.
3631 int sqlite3ExprCheckIN(Parse
*pParse
, Expr
*pIn
){
3632 int nVector
= sqlite3ExprVectorSize(pIn
->pLeft
);
3633 if( ExprUseXSelect(pIn
) && !pParse
->db
->mallocFailed
){
3634 if( nVector
!=pIn
->x
.pSelect
->pEList
->nExpr
){
3635 sqlite3SubselectError(pParse
, pIn
->x
.pSelect
->pEList
->nExpr
, nVector
);
3638 }else if( nVector
!=1 ){
3639 sqlite3VectorErrorMsg(pParse
, pIn
->pLeft
);
3646 #ifndef SQLITE_OMIT_SUBQUERY
3648 ** Generate code for an IN expression.
3650 ** x IN (SELECT ...)
3651 ** x IN (value, value, ...)
3653 ** The left-hand side (LHS) is a scalar or vector expression. The
3654 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3655 ** subquery. If the RHS is a subquery, the number of result columns must
3656 ** match the number of columns in the vector on the LHS. If the RHS is
3657 ** a list of values, the LHS must be a scalar.
3659 ** The IN operator is true if the LHS value is contained within the RHS.
3660 ** The result is false if the LHS is definitely not in the RHS. The
3661 ** result is NULL if the presence of the LHS in the RHS cannot be
3662 ** determined due to NULLs.
3664 ** This routine generates code that jumps to destIfFalse if the LHS is not
3665 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3666 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3667 ** within the RHS then fall through.
3669 ** See the separate in-operator.md documentation file in the canonical
3670 ** SQLite source tree for additional information.
3672 static void sqlite3ExprCodeIN(
3673 Parse
*pParse
, /* Parsing and code generating context */
3674 Expr
*pExpr
, /* The IN expression */
3675 int destIfFalse
, /* Jump here if LHS is not contained in the RHS */
3676 int destIfNull
/* Jump here if the results are unknown due to NULLs */
3678 int rRhsHasNull
= 0; /* Register that is true if RHS contains NULL values */
3679 int eType
; /* Type of the RHS */
3680 int rLhs
; /* Register(s) holding the LHS values */
3681 int rLhsOrig
; /* LHS values prior to reordering by aiMap[] */
3682 Vdbe
*v
; /* Statement under construction */
3683 int *aiMap
= 0; /* Map from vector field to index column */
3684 char *zAff
= 0; /* Affinity string for comparisons */
3685 int nVector
; /* Size of vectors for this IN operator */
3686 int iDummy
; /* Dummy parameter to exprCodeVector() */
3687 Expr
*pLeft
; /* The LHS of the IN operator */
3688 int i
; /* loop counter */
3689 int destStep2
; /* Where to jump when NULLs seen in step 2 */
3690 int destStep6
= 0; /* Start of code for Step 6 */
3691 int addrTruthOp
; /* Address of opcode that determines the IN is true */
3692 int destNotNull
; /* Jump here if a comparison is not true in step 6 */
3693 int addrTop
; /* Top of the step-6 loop */
3694 int iTab
= 0; /* Index to use */
3695 u8 okConstFactor
= pParse
->okConstFactor
;
3697 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
3698 pLeft
= pExpr
->pLeft
;
3699 if( sqlite3ExprCheckIN(pParse
, pExpr
) ) return;
3700 zAff
= exprINAffinity(pParse
, pExpr
);
3701 nVector
= sqlite3ExprVectorSize(pExpr
->pLeft
);
3702 aiMap
= (int*)sqlite3DbMallocZero(
3703 pParse
->db
, nVector
*(sizeof(int) + sizeof(char)) + 1
3705 if( pParse
->db
->mallocFailed
) goto sqlite3ExprCodeIN_oom_error
;
3707 /* Attempt to compute the RHS. After this step, if anything other than
3708 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3709 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3710 ** the RHS has not yet been coded. */
3712 assert( v
!=0 ); /* OOM detected prior to this routine */
3713 VdbeNoopComment((v
, "begin IN expr"));
3714 eType
= sqlite3FindInIndex(pParse
, pExpr
,
3715 IN_INDEX_MEMBERSHIP
| IN_INDEX_NOOP_OK
,
3716 destIfFalse
==destIfNull
? 0 : &rRhsHasNull
,
3719 assert( pParse
->nErr
|| nVector
==1 || eType
==IN_INDEX_EPH
3720 || eType
==IN_INDEX_INDEX_ASC
|| eType
==IN_INDEX_INDEX_DESC
3723 /* Confirm that aiMap[] contains nVector integer values between 0 and
3725 for(i
=0; i
<nVector
; i
++){
3727 for(cnt
=j
=0; j
<nVector
; j
++) if( aiMap
[j
]==i
) cnt
++;
3732 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3733 ** vector, then it is stored in an array of nVector registers starting
3736 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3737 ** so that the fields are in the same order as an existing index. The
3738 ** aiMap[] array contains a mapping from the original LHS field order to
3739 ** the field order that matches the RHS index.
3741 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3742 ** even if it is constant, as OP_Affinity may be used on the register
3743 ** by code generated below. */
3744 assert( pParse
->okConstFactor
==okConstFactor
);
3745 pParse
->okConstFactor
= 0;
3746 rLhsOrig
= exprCodeVector(pParse
, pLeft
, &iDummy
);
3747 pParse
->okConstFactor
= okConstFactor
;
3748 for(i
=0; i
<nVector
&& aiMap
[i
]==i
; i
++){} /* Are LHS fields reordered? */
3750 /* LHS fields are not reordered */
3753 /* Need to reorder the LHS fields according to aiMap */
3754 rLhs
= sqlite3GetTempRange(pParse
, nVector
);
3755 for(i
=0; i
<nVector
; i
++){
3756 sqlite3VdbeAddOp3(v
, OP_Copy
, rLhsOrig
+i
, rLhs
+aiMap
[i
], 0);
3760 /* If sqlite3FindInIndex() did not find or create an index that is
3761 ** suitable for evaluating the IN operator, then evaluate using a
3762 ** sequence of comparisons.
3764 ** This is step (1) in the in-operator.md optimized algorithm.
3766 if( eType
==IN_INDEX_NOOP
){
3769 int labelOk
= sqlite3VdbeMakeLabel(pParse
);
3773 assert( ExprUseXList(pExpr
) );
3774 pList
= pExpr
->x
.pList
;
3775 pColl
= sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
3776 if( destIfNull
!=destIfFalse
){
3777 regCkNull
= sqlite3GetTempReg(pParse
);
3778 sqlite3VdbeAddOp3(v
, OP_BitAnd
, rLhs
, rLhs
, regCkNull
);
3780 for(ii
=0; ii
<pList
->nExpr
; ii
++){
3781 r2
= sqlite3ExprCodeTemp(pParse
, pList
->a
[ii
].pExpr
, ®ToFree
);
3782 if( regCkNull
&& sqlite3ExprCanBeNull(pList
->a
[ii
].pExpr
) ){
3783 sqlite3VdbeAddOp3(v
, OP_BitAnd
, regCkNull
, r2
, regCkNull
);
3785 sqlite3ReleaseTempReg(pParse
, regToFree
);
3786 if( ii
<pList
->nExpr
-1 || destIfNull
!=destIfFalse
){
3787 int op
= rLhs
!=r2
? OP_Eq
: OP_NotNull
;
3788 sqlite3VdbeAddOp4(v
, op
, rLhs
, labelOk
, r2
,
3789 (void*)pColl
, P4_COLLSEQ
);
3790 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1 && op
==OP_Eq
);
3791 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1 && op
==OP_Eq
);
3792 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1 && op
==OP_NotNull
);
3793 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1 && op
==OP_NotNull
);
3794 sqlite3VdbeChangeP5(v
, zAff
[0]);
3796 int op
= rLhs
!=r2
? OP_Ne
: OP_IsNull
;
3797 assert( destIfNull
==destIfFalse
);
3798 sqlite3VdbeAddOp4(v
, op
, rLhs
, destIfFalse
, r2
,
3799 (void*)pColl
, P4_COLLSEQ
);
3800 VdbeCoverageIf(v
, op
==OP_Ne
);
3801 VdbeCoverageIf(v
, op
==OP_IsNull
);
3802 sqlite3VdbeChangeP5(v
, zAff
[0] | SQLITE_JUMPIFNULL
);
3806 sqlite3VdbeAddOp2(v
, OP_IsNull
, regCkNull
, destIfNull
); VdbeCoverage(v
);
3807 sqlite3VdbeGoto(v
, destIfFalse
);
3809 sqlite3VdbeResolveLabel(v
, labelOk
);
3810 sqlite3ReleaseTempReg(pParse
, regCkNull
);
3811 goto sqlite3ExprCodeIN_finished
;
3814 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3815 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3816 ** We will then skip the binary search of the RHS.
3818 if( destIfNull
==destIfFalse
){
3819 destStep2
= destIfFalse
;
3821 destStep2
= destStep6
= sqlite3VdbeMakeLabel(pParse
);
3823 for(i
=0; i
<nVector
; i
++){
3824 Expr
*p
= sqlite3VectorFieldSubexpr(pExpr
->pLeft
, i
);
3825 if( pParse
->nErr
) goto sqlite3ExprCodeIN_oom_error
;
3826 if( sqlite3ExprCanBeNull(p
) ){
3827 sqlite3VdbeAddOp2(v
, OP_IsNull
, rLhs
+i
, destStep2
);
3832 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3833 ** of the RHS using the LHS as a probe. If found, the result is
3836 if( eType
==IN_INDEX_ROWID
){
3837 /* In this case, the RHS is the ROWID of table b-tree and so we also
3838 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3839 ** into a single opcode. */
3840 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, iTab
, destIfFalse
, rLhs
);
3842 addrTruthOp
= sqlite3VdbeAddOp0(v
, OP_Goto
); /* Return True */
3844 sqlite3VdbeAddOp4(v
, OP_Affinity
, rLhs
, nVector
, 0, zAff
, nVector
);
3845 if( destIfFalse
==destIfNull
){
3846 /* Combine Step 3 and Step 5 into a single opcode */
3847 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, iTab
, destIfFalse
,
3848 rLhs
, nVector
); VdbeCoverage(v
);
3849 goto sqlite3ExprCodeIN_finished
;
3851 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3852 addrTruthOp
= sqlite3VdbeAddOp4Int(v
, OP_Found
, iTab
, 0,
3853 rLhs
, nVector
); VdbeCoverage(v
);
3856 /* Step 4. If the RHS is known to be non-NULL and we did not find
3857 ** an match on the search above, then the result must be FALSE.
3859 if( rRhsHasNull
&& nVector
==1 ){
3860 sqlite3VdbeAddOp2(v
, OP_NotNull
, rRhsHasNull
, destIfFalse
);
3864 /* Step 5. If we do not care about the difference between NULL and
3865 ** FALSE, then just return false.
3867 if( destIfFalse
==destIfNull
) sqlite3VdbeGoto(v
, destIfFalse
);
3869 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3870 ** If any comparison is NULL, then the result is NULL. If all
3871 ** comparisons are FALSE then the final result is FALSE.
3873 ** For a scalar LHS, it is sufficient to check just the first row
3876 if( destStep6
) sqlite3VdbeResolveLabel(v
, destStep6
);
3877 addrTop
= sqlite3VdbeAddOp2(v
, OP_Rewind
, iTab
, destIfFalse
);
3880 destNotNull
= sqlite3VdbeMakeLabel(pParse
);
3882 /* For nVector==1, combine steps 6 and 7 by immediately returning
3883 ** FALSE if the first comparison is not NULL */
3884 destNotNull
= destIfFalse
;
3886 for(i
=0; i
<nVector
; i
++){
3889 int r3
= sqlite3GetTempReg(pParse
);
3890 p
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3891 pColl
= sqlite3ExprCollSeq(pParse
, p
);
3892 sqlite3VdbeAddOp3(v
, OP_Column
, iTab
, i
, r3
);
3893 sqlite3VdbeAddOp4(v
, OP_Ne
, rLhs
+i
, destNotNull
, r3
,
3894 (void*)pColl
, P4_COLLSEQ
);
3896 sqlite3ReleaseTempReg(pParse
, r3
);
3898 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfNull
);
3900 sqlite3VdbeResolveLabel(v
, destNotNull
);
3901 sqlite3VdbeAddOp2(v
, OP_Next
, iTab
, addrTop
+1);
3904 /* Step 7: If we reach this point, we know that the result must
3906 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfFalse
);
3909 /* Jumps here in order to return true. */
3910 sqlite3VdbeJumpHere(v
, addrTruthOp
);
3912 sqlite3ExprCodeIN_finished
:
3913 if( rLhs
!=rLhsOrig
) sqlite3ReleaseTempReg(pParse
, rLhs
);
3914 VdbeComment((v
, "end IN expr"));
3915 sqlite3ExprCodeIN_oom_error
:
3916 sqlite3DbFree(pParse
->db
, aiMap
);
3917 sqlite3DbFree(pParse
->db
, zAff
);
3919 #endif /* SQLITE_OMIT_SUBQUERY */
3921 #ifndef SQLITE_OMIT_FLOATING_POINT
3923 ** Generate an instruction that will put the floating point
3924 ** value described by z[0..n-1] into register iMem.
3926 ** The z[] string will probably not be zero-terminated. But the
3927 ** z[n] character is guaranteed to be something that does not look
3928 ** like the continuation of the number.
3930 static void codeReal(Vdbe
*v
, const char *z
, int negateFlag
, int iMem
){
3933 sqlite3AtoF(z
, &value
, sqlite3Strlen30(z
), SQLITE_UTF8
);
3934 assert( !sqlite3IsNaN(value
) ); /* The new AtoF never returns NaN */
3935 if( negateFlag
) value
= -value
;
3936 sqlite3VdbeAddOp4Dup8(v
, OP_Real
, 0, iMem
, 0, (u8
*)&value
, P4_REAL
);
3943 ** Generate an instruction that will put the integer describe by
3944 ** text z[0..n-1] into register iMem.
3946 ** Expr.u.zToken is always UTF8 and zero-terminated.
3948 static void codeInteger(Parse
*pParse
, Expr
*pExpr
, int negFlag
, int iMem
){
3949 Vdbe
*v
= pParse
->pVdbe
;
3950 if( pExpr
->flags
& EP_IntValue
){
3951 int i
= pExpr
->u
.iValue
;
3953 if( negFlag
) i
= -i
;
3954 sqlite3VdbeAddOp2(v
, OP_Integer
, i
, iMem
);
3958 const char *z
= pExpr
->u
.zToken
;
3960 c
= sqlite3DecOrHexToI64(z
, &value
);
3961 if( (c
==3 && !negFlag
) || (c
==2) || (negFlag
&& value
==SMALLEST_INT64
)){
3962 #ifdef SQLITE_OMIT_FLOATING_POINT
3963 sqlite3ErrorMsg(pParse
, "oversized integer: %s%#T", negFlag
?"-":"",pExpr
);
3965 #ifndef SQLITE_OMIT_HEX_INTEGER
3966 if( sqlite3_strnicmp(z
,"0x",2)==0 ){
3967 sqlite3ErrorMsg(pParse
, "hex literal too big: %s%#T",
3968 negFlag
?"-":"",pExpr
);
3972 codeReal(v
, z
, negFlag
, iMem
);
3976 if( negFlag
){ value
= c
==3 ? SMALLEST_INT64
: -value
; }
3977 sqlite3VdbeAddOp4Dup8(v
, OP_Int64
, 0, iMem
, 0, (u8
*)&value
, P4_INT64
);
3983 /* Generate code that will load into register regOut a value that is
3984 ** appropriate for the iIdxCol-th column of index pIdx.
3986 void sqlite3ExprCodeLoadIndexColumn(
3987 Parse
*pParse
, /* The parsing context */
3988 Index
*pIdx
, /* The index whose column is to be loaded */
3989 int iTabCur
, /* Cursor pointing to a table row */
3990 int iIdxCol
, /* The column of the index to be loaded */
3991 int regOut
/* Store the index column value in this register */
3993 i16 iTabCol
= pIdx
->aiColumn
[iIdxCol
];
3994 if( iTabCol
==XN_EXPR
){
3995 assert( pIdx
->aColExpr
);
3996 assert( pIdx
->aColExpr
->nExpr
>iIdxCol
);
3997 pParse
->iSelfTab
= iTabCur
+ 1;
3998 sqlite3ExprCodeCopy(pParse
, pIdx
->aColExpr
->a
[iIdxCol
].pExpr
, regOut
);
3999 pParse
->iSelfTab
= 0;
4001 sqlite3ExprCodeGetColumnOfTable(pParse
->pVdbe
, pIdx
->pTable
, iTabCur
,
4006 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4008 ** Generate code that will compute the value of generated column pCol
4009 ** and store the result in register regOut
4011 void sqlite3ExprCodeGeneratedColumn(
4012 Parse
*pParse
, /* Parsing context */
4013 Table
*pTab
, /* Table containing the generated column */
4014 Column
*pCol
, /* The generated column */
4015 int regOut
/* Put the result in this register */
4018 Vdbe
*v
= pParse
->pVdbe
;
4019 int nErr
= pParse
->nErr
;
4021 assert( pParse
->iSelfTab
!=0 );
4022 if( pParse
->iSelfTab
>0 ){
4023 iAddr
= sqlite3VdbeAddOp3(v
, OP_IfNullRow
, pParse
->iSelfTab
-1, 0, regOut
);
4027 sqlite3ExprCodeCopy(pParse
, sqlite3ColumnExpr(pTab
,pCol
), regOut
);
4028 if( pCol
->affinity
>=SQLITE_AFF_TEXT
){
4029 sqlite3VdbeAddOp4(v
, OP_Affinity
, regOut
, 1, 0, &pCol
->affinity
, 1);
4031 if( iAddr
) sqlite3VdbeJumpHere(v
, iAddr
);
4032 if( pParse
->nErr
>nErr
) pParse
->db
->errByteOffset
= -1;
4034 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4037 ** Generate code to extract the value of the iCol-th column of a table.
4039 void sqlite3ExprCodeGetColumnOfTable(
4040 Vdbe
*v
, /* Parsing context */
4041 Table
*pTab
, /* The table containing the value */
4042 int iTabCur
, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
4043 int iCol
, /* Index of the column to extract */
4044 int regOut
/* Extract the value into this register */
4049 assert( iCol
!=XN_EXPR
);
4050 if( iCol
<0 || iCol
==pTab
->iPKey
){
4051 sqlite3VdbeAddOp2(v
, OP_Rowid
, iTabCur
, regOut
);
4052 VdbeComment((v
, "%s.rowid", pTab
->zName
));
4056 if( IsVirtual(pTab
) ){
4059 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4060 }else if( (pCol
= &pTab
->aCol
[iCol
])->colFlags
& COLFLAG_VIRTUAL
){
4061 Parse
*pParse
= sqlite3VdbeParser(v
);
4062 if( pCol
->colFlags
& COLFLAG_BUSY
){
4063 sqlite3ErrorMsg(pParse
, "generated column loop on \"%s\"",
4066 int savedSelfTab
= pParse
->iSelfTab
;
4067 pCol
->colFlags
|= COLFLAG_BUSY
;
4068 pParse
->iSelfTab
= iTabCur
+1;
4069 sqlite3ExprCodeGeneratedColumn(pParse
, pTab
, pCol
, regOut
);
4070 pParse
->iSelfTab
= savedSelfTab
;
4071 pCol
->colFlags
&= ~COLFLAG_BUSY
;
4075 }else if( !HasRowid(pTab
) ){
4076 testcase( iCol
!=sqlite3TableColumnToStorage(pTab
, iCol
) );
4077 x
= sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab
), iCol
);
4080 x
= sqlite3TableColumnToStorage(pTab
,iCol
);
4081 testcase( x
!=iCol
);
4084 sqlite3VdbeAddOp3(v
, op
, iTabCur
, x
, regOut
);
4085 sqlite3ColumnDefault(v
, pTab
, iCol
, regOut
);
4090 ** Generate code that will extract the iColumn-th column from
4091 ** table pTab and store the column value in register iReg.
4093 ** There must be an open cursor to pTab in iTable when this routine
4094 ** is called. If iColumn<0 then code is generated that extracts the rowid.
4096 int sqlite3ExprCodeGetColumn(
4097 Parse
*pParse
, /* Parsing and code generating context */
4098 Table
*pTab
, /* Description of the table we are reading from */
4099 int iColumn
, /* Index of the table column */
4100 int iTable
, /* The cursor pointing to the table */
4101 int iReg
, /* Store results here */
4102 u8 p5
/* P5 value for OP_Column + FLAGS */
4104 assert( pParse
->pVdbe
!=0 );
4105 assert( (p5
& (OPFLAG_NOCHNG
|OPFLAG_TYPEOFARG
|OPFLAG_LENGTHARG
))==p5
);
4106 assert( IsVirtual(pTab
) || (p5
& OPFLAG_NOCHNG
)==0 );
4107 sqlite3ExprCodeGetColumnOfTable(pParse
->pVdbe
, pTab
, iTable
, iColumn
, iReg
);
4109 VdbeOp
*pOp
= sqlite3VdbeGetLastOp(pParse
->pVdbe
);
4110 if( pOp
->opcode
==OP_Column
) pOp
->p5
= p5
;
4111 if( pOp
->opcode
==OP_VColumn
) pOp
->p5
= (p5
& OPFLAG_NOCHNG
);
4117 ** Generate code to move content from registers iFrom...iFrom+nReg-1
4118 ** over to iTo..iTo+nReg-1.
4120 void sqlite3ExprCodeMove(Parse
*pParse
, int iFrom
, int iTo
, int nReg
){
4121 sqlite3VdbeAddOp3(pParse
->pVdbe
, OP_Move
, iFrom
, iTo
, nReg
);
4125 ** Convert a scalar expression node to a TK_REGISTER referencing
4126 ** register iReg. The caller must ensure that iReg already contains
4127 ** the correct value for the expression.
4129 static void exprToRegister(Expr
*pExpr
, int iReg
){
4130 Expr
*p
= sqlite3ExprSkipCollateAndLikely(pExpr
);
4131 if( NEVER(p
==0) ) return;
4133 p
->op
= TK_REGISTER
;
4135 ExprClearProperty(p
, EP_Skip
);
4139 ** Evaluate an expression (either a vector or a scalar expression) and store
4140 ** the result in contiguous temporary registers. Return the index of
4141 ** the first register used to store the result.
4143 ** If the returned result register is a temporary scalar, then also write
4144 ** that register number into *piFreeable. If the returned result register
4145 ** is not a temporary or if the expression is a vector set *piFreeable
4148 static int exprCodeVector(Parse
*pParse
, Expr
*p
, int *piFreeable
){
4150 int nResult
= sqlite3ExprVectorSize(p
);
4152 iResult
= sqlite3ExprCodeTemp(pParse
, p
, piFreeable
);
4155 if( p
->op
==TK_SELECT
){
4156 #if SQLITE_OMIT_SUBQUERY
4159 iResult
= sqlite3CodeSubselect(pParse
, p
);
4163 iResult
= pParse
->nMem
+1;
4164 pParse
->nMem
+= nResult
;
4165 assert( ExprUseXList(p
) );
4166 for(i
=0; i
<nResult
; i
++){
4167 sqlite3ExprCodeFactorable(pParse
, p
->x
.pList
->a
[i
].pExpr
, i
+iResult
);
4175 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
4176 ** so that a subsequent copy will not be merged into this one.
4178 static void setDoNotMergeFlagOnCopy(Vdbe
*v
){
4179 if( sqlite3VdbeGetLastOp(v
)->opcode
==OP_Copy
){
4180 sqlite3VdbeChangeP5(v
, 1); /* Tag trailing OP_Copy as not mergeable */
4185 ** Generate code to implement special SQL functions that are implemented
4186 ** in-line rather than by using the usual callbacks.
4188 static int exprCodeInlineFunction(
4189 Parse
*pParse
, /* Parsing context */
4190 ExprList
*pFarg
, /* List of function arguments */
4191 int iFuncId
, /* Function ID. One of the INTFUNC_... values */
4192 int target
/* Store function result in this register */
4195 Vdbe
*v
= pParse
->pVdbe
;
4198 nFarg
= pFarg
->nExpr
;
4199 assert( nFarg
>0 ); /* All in-line functions have at least one argument */
4201 case INLINEFUNC_coalesce
: {
4202 /* Attempt a direct implementation of the built-in COALESCE() and
4203 ** IFNULL() functions. This avoids unnecessary evaluation of
4204 ** arguments past the first non-NULL argument.
4206 int endCoalesce
= sqlite3VdbeMakeLabel(pParse
);
4209 sqlite3ExprCode(pParse
, pFarg
->a
[0].pExpr
, target
);
4210 for(i
=1; i
<nFarg
; i
++){
4211 sqlite3VdbeAddOp2(v
, OP_NotNull
, target
, endCoalesce
);
4213 sqlite3ExprCode(pParse
, pFarg
->a
[i
].pExpr
, target
);
4215 setDoNotMergeFlagOnCopy(v
);
4216 sqlite3VdbeResolveLabel(v
, endCoalesce
);
4219 case INLINEFUNC_iif
: {
4221 memset(&caseExpr
, 0, sizeof(caseExpr
));
4222 caseExpr
.op
= TK_CASE
;
4223 caseExpr
.x
.pList
= pFarg
;
4224 return sqlite3ExprCodeTarget(pParse
, &caseExpr
, target
);
4226 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4227 case INLINEFUNC_sqlite_offset
: {
4228 Expr
*pArg
= pFarg
->a
[0].pExpr
;
4229 if( pArg
->op
==TK_COLUMN
&& pArg
->iTable
>=0 ){
4230 sqlite3VdbeAddOp3(v
, OP_Offset
, pArg
->iTable
, pArg
->iColumn
, target
);
4232 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4238 /* The UNLIKELY() function is a no-op. The result is the value
4239 ** of the first argument.
4241 assert( nFarg
==1 || nFarg
==2 );
4242 target
= sqlite3ExprCodeTarget(pParse
, pFarg
->a
[0].pExpr
, target
);
4246 /***********************************************************************
4247 ** Test-only SQL functions that are only usable if enabled
4248 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4250 #if !defined(SQLITE_UNTESTABLE)
4251 case INLINEFUNC_expr_compare
: {
4252 /* Compare two expressions using sqlite3ExprCompare() */
4254 sqlite3VdbeAddOp2(v
, OP_Integer
,
4255 sqlite3ExprCompare(0,pFarg
->a
[0].pExpr
, pFarg
->a
[1].pExpr
,-1),
4260 case INLINEFUNC_expr_implies_expr
: {
4261 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4263 sqlite3VdbeAddOp2(v
, OP_Integer
,
4264 sqlite3ExprImpliesExpr(pParse
,pFarg
->a
[0].pExpr
, pFarg
->a
[1].pExpr
,-1),
4269 case INLINEFUNC_implies_nonnull_row
: {
4270 /* Result of sqlite3ExprImpliesNonNullRow() */
4273 pA1
= pFarg
->a
[1].pExpr
;
4274 if( pA1
->op
==TK_COLUMN
){
4275 sqlite3VdbeAddOp2(v
, OP_Integer
,
4276 sqlite3ExprImpliesNonNullRow(pFarg
->a
[0].pExpr
,pA1
->iTable
,1),
4279 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4284 case INLINEFUNC_affinity
: {
4285 /* The AFFINITY() function evaluates to a string that describes
4286 ** the type affinity of the argument. This is used for testing of
4287 ** the SQLite type logic.
4289 const char *azAff
[] = { "blob", "text", "numeric", "integer",
4290 "real", "flexnum" };
4293 aff
= sqlite3ExprAffinity(pFarg
->a
[0].pExpr
);
4294 assert( aff
<=SQLITE_AFF_NONE
4295 || (aff
>=SQLITE_AFF_BLOB
&& aff
<=SQLITE_AFF_FLEXNUM
) );
4296 sqlite3VdbeLoadString(v
, target
,
4297 (aff
<=SQLITE_AFF_NONE
) ? "none" : azAff
[aff
-SQLITE_AFF_BLOB
]);
4300 #endif /* !defined(SQLITE_UNTESTABLE) */
4306 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4307 ** If it is, then resolve the expression by reading from the index and
4308 ** return the register into which the value has been read. If pExpr is
4309 ** not an indexed expression, then return negative.
4311 static SQLITE_NOINLINE
int sqlite3IndexedExprLookup(
4312 Parse
*pParse
, /* The parsing context */
4313 Expr
*pExpr
, /* The expression to potentially bypass */
4314 int target
/* Where to store the result of the expression */
4318 for(p
=pParse
->pIdxEpr
; p
; p
=p
->pIENext
){
4320 int iDataCur
= p
->iDataCur
;
4321 if( iDataCur
<0 ) continue;
4322 if( pParse
->iSelfTab
){
4323 if( p
->iDataCur
!=pParse
->iSelfTab
-1 ) continue;
4326 if( sqlite3ExprCompare(0, pExpr
, p
->pExpr
, iDataCur
)!=0 ) continue;
4327 assert( p
->aff
>=SQLITE_AFF_BLOB
&& p
->aff
<=SQLITE_AFF_NUMERIC
);
4328 exprAff
= sqlite3ExprAffinity(pExpr
);
4329 if( (exprAff
<=SQLITE_AFF_BLOB
&& p
->aff
!=SQLITE_AFF_BLOB
)
4330 || (exprAff
==SQLITE_AFF_TEXT
&& p
->aff
!=SQLITE_AFF_TEXT
)
4331 || (exprAff
>=SQLITE_AFF_NUMERIC
&& p
->aff
!=SQLITE_AFF_NUMERIC
)
4333 /* Affinity mismatch on a generated column */
4339 if( p
->bMaybeNullRow
){
4340 /* If the index is on a NULL row due to an outer join, then we
4341 ** cannot extract the value from the index. The value must be
4342 ** computed using the original expression. */
4343 int addr
= sqlite3VdbeCurrentAddr(v
);
4344 sqlite3VdbeAddOp3(v
, OP_IfNullRow
, p
->iIdxCur
, addr
+3, target
);
4346 sqlite3VdbeAddOp3(v
, OP_Column
, p
->iIdxCur
, p
->iIdxCol
, target
);
4347 VdbeComment((v
, "%s expr-column %d", p
->zIdxName
, p
->iIdxCol
));
4348 sqlite3VdbeGoto(v
, 0);
4349 p
= pParse
->pIdxEpr
;
4350 pParse
->pIdxEpr
= 0;
4351 sqlite3ExprCode(pParse
, pExpr
, target
);
4352 pParse
->pIdxEpr
= p
;
4353 sqlite3VdbeJumpHere(v
, addr
+2);
4355 sqlite3VdbeAddOp3(v
, OP_Column
, p
->iIdxCur
, p
->iIdxCol
, target
);
4356 VdbeComment((v
, "%s expr-column %d", p
->zIdxName
, p
->iIdxCol
));
4360 return -1; /* Not found */
4365 ** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This
4366 ** function checks the Parse.pIdxPartExpr list to see if this column
4367 ** can be replaced with a constant value. If so, it generates code to
4368 ** put the constant value in a register (ideally, but not necessarily,
4369 ** register iTarget) and returns the register number.
4371 ** Or, if the TK_COLUMN cannot be replaced by a constant, zero is
4374 static int exprPartidxExprLookup(Parse
*pParse
, Expr
*pExpr
, int iTarget
){
4376 for(p
=pParse
->pIdxPartExpr
; p
; p
=p
->pIENext
){
4377 if( pExpr
->iColumn
==p
->iIdxCol
&& pExpr
->iTable
==p
->iDataCur
){
4378 Vdbe
*v
= pParse
->pVdbe
;
4382 if( p
->bMaybeNullRow
){
4383 addr
= sqlite3VdbeAddOp1(v
, OP_IfNullRow
, p
->iIdxCur
);
4385 ret
= sqlite3ExprCodeTarget(pParse
, p
->pExpr
, iTarget
);
4386 sqlite3VdbeAddOp4(pParse
->pVdbe
, OP_Affinity
, ret
, 1, 0,
4387 (const char*)&p
->aff
, 1);
4389 sqlite3VdbeJumpHere(v
, addr
);
4390 sqlite3VdbeChangeP3(v
, addr
, ret
);
4400 ** Generate code into the current Vdbe to evaluate the given
4401 ** expression. Attempt to store the results in register "target".
4402 ** Return the register where results are stored.
4404 ** With this routine, there is no guarantee that results will
4405 ** be stored in target. The result might be stored in some other
4406 ** register if it is convenient to do so. The calling function
4407 ** must check the return code and move the results to the desired
4410 int sqlite3ExprCodeTarget(Parse
*pParse
, Expr
*pExpr
, int target
){
4411 Vdbe
*v
= pParse
->pVdbe
; /* The VM under construction */
4412 int op
; /* The opcode being coded */
4413 int inReg
= target
; /* Results stored in register inReg */
4414 int regFree1
= 0; /* If non-zero free this temporary register */
4415 int regFree2
= 0; /* If non-zero free this temporary register */
4416 int r1
, r2
; /* Various register numbers */
4417 Expr tempX
; /* Temporary expression node */
4420 assert( target
>0 && target
<=pParse
->nMem
);
4426 }else if( pParse
->pIdxEpr
!=0
4427 && !ExprHasProperty(pExpr
, EP_Leaf
)
4428 && (r1
= sqlite3IndexedExprLookup(pParse
, pExpr
, target
))>=0
4432 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
4435 assert( op
!=TK_ORDER
);
4437 case TK_AGG_COLUMN
: {
4438 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
4439 struct AggInfo_col
*pCol
;
4440 assert( pAggInfo
!=0 );
4441 assert( pExpr
->iAgg
>=0 );
4442 if( pExpr
->iAgg
>=pAggInfo
->nColumn
){
4443 /* Happens when the left table of a RIGHT JOIN is null and
4444 ** is using an expression index */
4445 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4446 #ifdef SQLITE_VDBE_COVERAGE
4447 /* Verify that the OP_Null above is exercised by tests
4448 ** tag-20230325-2 */
4449 sqlite3VdbeAddOp3(v
, OP_NotNull
, target
, 1, 20230325);
4450 VdbeCoverageNeverTaken(v
);
4454 pCol
= &pAggInfo
->aCol
[pExpr
->iAgg
];
4455 if( !pAggInfo
->directMode
){
4456 return AggInfoColumnReg(pAggInfo
, pExpr
->iAgg
);
4457 }else if( pAggInfo
->useSortingIdx
){
4458 Table
*pTab
= pCol
->pTab
;
4459 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
4460 pCol
->iSorterColumn
, target
);
4462 /* No comment added */
4463 }else if( pCol
->iColumn
<0 ){
4464 VdbeComment((v
,"%s.rowid",pTab
->zName
));
4466 VdbeComment((v
,"%s.%s",
4467 pTab
->zName
, pTab
->aCol
[pCol
->iColumn
].zCnName
));
4468 if( pTab
->aCol
[pCol
->iColumn
].affinity
==SQLITE_AFF_REAL
){
4469 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4473 }else if( pExpr
->y
.pTab
==0 ){
4474 /* This case happens when the argument to an aggregate function
4475 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4476 sqlite3VdbeAddOp3(v
, OP_Column
, pExpr
->iTable
, pExpr
->iColumn
, target
);
4479 /* Otherwise, fall thru into the TK_COLUMN case */
4480 /* no break */ deliberate_fall_through
4483 int iTab
= pExpr
->iTable
;
4485 if( ExprHasProperty(pExpr
, EP_FixedCol
) ){
4486 /* This COLUMN expression is really a constant due to WHERE clause
4487 ** constraints, and that constant is coded by the pExpr->pLeft
4488 ** expression. However, make sure the constant has the correct
4489 ** datatype by applying the Affinity of the table column to the
4493 iReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
,target
);
4494 assert( ExprUseYTab(pExpr
) );
4495 assert( pExpr
->y
.pTab
!=0 );
4496 aff
= sqlite3TableColumnAffinity(pExpr
->y
.pTab
, pExpr
->iColumn
);
4497 if( aff
>SQLITE_AFF_BLOB
){
4498 static const char zAff
[] = "B\000C\000D\000E\000F";
4499 assert( SQLITE_AFF_BLOB
=='A' );
4500 assert( SQLITE_AFF_TEXT
=='B' );
4501 sqlite3VdbeAddOp4(v
, OP_Affinity
, iReg
, 1, 0,
4502 &zAff
[(aff
-'B')*2], P4_STATIC
);
4507 if( pParse
->iSelfTab
<0 ){
4508 /* Other columns in the same row for CHECK constraints or
4509 ** generated columns or for inserting into partial index.
4510 ** The row is unpacked into registers beginning at
4511 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4512 ** immediately prior to the first column.
4517 int iCol
= pExpr
->iColumn
;
4518 assert( ExprUseYTab(pExpr
) );
4519 pTab
= pExpr
->y
.pTab
;
4521 assert( iCol
>=XN_ROWID
);
4522 assert( iCol
<pTab
->nCol
);
4524 return -1-pParse
->iSelfTab
;
4526 pCol
= pTab
->aCol
+ iCol
;
4527 testcase( iCol
!=sqlite3TableColumnToStorage(pTab
,iCol
) );
4528 iSrc
= sqlite3TableColumnToStorage(pTab
, iCol
) - pParse
->iSelfTab
;
4529 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4530 if( pCol
->colFlags
& COLFLAG_GENERATED
){
4531 if( pCol
->colFlags
& COLFLAG_BUSY
){
4532 sqlite3ErrorMsg(pParse
, "generated column loop on \"%s\"",
4536 pCol
->colFlags
|= COLFLAG_BUSY
;
4537 if( pCol
->colFlags
& COLFLAG_NOTAVAIL
){
4538 sqlite3ExprCodeGeneratedColumn(pParse
, pTab
, pCol
, iSrc
);
4540 pCol
->colFlags
&= ~(COLFLAG_BUSY
|COLFLAG_NOTAVAIL
);
4543 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4544 if( pCol
->affinity
==SQLITE_AFF_REAL
){
4545 sqlite3VdbeAddOp2(v
, OP_SCopy
, iSrc
, target
);
4546 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4552 /* Coding an expression that is part of an index where column names
4553 ** in the index refer to the table to which the index belongs */
4554 iTab
= pParse
->iSelfTab
- 1;
4557 else if( pParse
->pIdxPartExpr
4558 && 0!=(r1
= exprPartidxExprLookup(pParse
, pExpr
, target
))
4562 assert( ExprUseYTab(pExpr
) );
4563 assert( pExpr
->y
.pTab
!=0 );
4564 iReg
= sqlite3ExprCodeGetColumn(pParse
, pExpr
->y
.pTab
,
4565 pExpr
->iColumn
, iTab
, target
,
4570 codeInteger(pParse
, pExpr
, 0, target
);
4573 case TK_TRUEFALSE
: {
4574 sqlite3VdbeAddOp2(v
, OP_Integer
, sqlite3ExprTruthValue(pExpr
), target
);
4577 #ifndef SQLITE_OMIT_FLOATING_POINT
4579 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4580 codeReal(v
, pExpr
->u
.zToken
, 0, target
);
4585 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4586 sqlite3VdbeLoadString(v
, target
, pExpr
->u
.zToken
);
4590 /* Make NULL the default case so that if a bug causes an illegal
4591 ** Expr node to be passed into this function, it will be handled
4592 ** sanely and not crash. But keep the assert() to bring the problem
4593 ** to the attention of the developers. */
4594 assert( op
==TK_NULL
|| op
==TK_ERROR
|| pParse
->db
->mallocFailed
);
4595 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4598 #ifndef SQLITE_OMIT_BLOB_LITERAL
4603 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4604 assert( pExpr
->u
.zToken
[0]=='x' || pExpr
->u
.zToken
[0]=='X' );
4605 assert( pExpr
->u
.zToken
[1]=='\'' );
4606 z
= &pExpr
->u
.zToken
[2];
4607 n
= sqlite3Strlen30(z
) - 1;
4608 assert( z
[n
]=='\'' );
4609 zBlob
= sqlite3HexToBlob(sqlite3VdbeDb(v
), z
, n
);
4610 sqlite3VdbeAddOp4(v
, OP_Blob
, n
/2, target
, 0, zBlob
, P4_DYNAMIC
);
4615 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4616 assert( pExpr
->u
.zToken
!=0 );
4617 assert( pExpr
->u
.zToken
[0]!=0 );
4618 sqlite3VdbeAddOp2(v
, OP_Variable
, pExpr
->iColumn
, target
);
4619 if( pExpr
->u
.zToken
[1]!=0 ){
4620 const char *z
= sqlite3VListNumToName(pParse
->pVList
, pExpr
->iColumn
);
4621 assert( pExpr
->u
.zToken
[0]=='?' || (z
&& !strcmp(pExpr
->u
.zToken
, z
)) );
4622 pParse
->pVList
[0] = 0; /* Indicate VList may no longer be enlarged */
4623 sqlite3VdbeAppendP4(v
, (char*)z
, P4_STATIC
);
4628 return pExpr
->iTable
;
4630 #ifndef SQLITE_OMIT_CAST
4632 /* Expressions of the form: CAST(pLeft AS token) */
4633 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
4634 assert( inReg
==target
);
4635 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4636 sqlite3VdbeAddOp2(v
, OP_Cast
, target
,
4637 sqlite3AffinityType(pExpr
->u
.zToken
, 0));
4640 #endif /* SQLITE_OMIT_CAST */
4643 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
4652 Expr
*pLeft
= pExpr
->pLeft
;
4653 if( sqlite3ExprIsVector(pLeft
) ){
4654 codeVectorCompare(pParse
, pExpr
, target
, op
, p5
);
4656 r1
= sqlite3ExprCodeTemp(pParse
, pLeft
, ®Free1
);
4657 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
4658 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, inReg
);
4659 codeCompare(pParse
, pLeft
, pExpr
->pRight
, op
, r1
, r2
,
4660 sqlite3VdbeCurrentAddr(v
)+2, p5
,
4661 ExprHasProperty(pExpr
,EP_Commuted
));
4662 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
4663 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
4664 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
4665 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
4666 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
4667 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
4668 if( p5
==SQLITE_NULLEQ
){
4669 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, inReg
);
4671 sqlite3VdbeAddOp3(v
, OP_ZeroOrNull
, r1
, inReg
, r2
);
4673 testcase( regFree1
==0 );
4674 testcase( regFree2
==0 );
4690 assert( TK_AND
==OP_And
); testcase( op
==TK_AND
);
4691 assert( TK_OR
==OP_Or
); testcase( op
==TK_OR
);
4692 assert( TK_PLUS
==OP_Add
); testcase( op
==TK_PLUS
);
4693 assert( TK_MINUS
==OP_Subtract
); testcase( op
==TK_MINUS
);
4694 assert( TK_REM
==OP_Remainder
); testcase( op
==TK_REM
);
4695 assert( TK_BITAND
==OP_BitAnd
); testcase( op
==TK_BITAND
);
4696 assert( TK_BITOR
==OP_BitOr
); testcase( op
==TK_BITOR
);
4697 assert( TK_SLASH
==OP_Divide
); testcase( op
==TK_SLASH
);
4698 assert( TK_LSHIFT
==OP_ShiftLeft
); testcase( op
==TK_LSHIFT
);
4699 assert( TK_RSHIFT
==OP_ShiftRight
); testcase( op
==TK_RSHIFT
);
4700 assert( TK_CONCAT
==OP_Concat
); testcase( op
==TK_CONCAT
);
4701 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4702 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
4703 sqlite3VdbeAddOp3(v
, op
, r2
, r1
, target
);
4704 testcase( regFree1
==0 );
4705 testcase( regFree2
==0 );
4709 Expr
*pLeft
= pExpr
->pLeft
;
4711 if( pLeft
->op
==TK_INTEGER
){
4712 codeInteger(pParse
, pLeft
, 1, target
);
4714 #ifndef SQLITE_OMIT_FLOATING_POINT
4715 }else if( pLeft
->op
==TK_FLOAT
){
4716 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4717 codeReal(v
, pLeft
->u
.zToken
, 1, target
);
4721 tempX
.op
= TK_INTEGER
;
4722 tempX
.flags
= EP_IntValue
|EP_TokenOnly
;
4724 ExprClearVVAProperties(&tempX
);
4725 r1
= sqlite3ExprCodeTemp(pParse
, &tempX
, ®Free1
);
4726 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free2
);
4727 sqlite3VdbeAddOp3(v
, OP_Subtract
, r2
, r1
, target
);
4728 testcase( regFree2
==0 );
4734 assert( TK_BITNOT
==OP_BitNot
); testcase( op
==TK_BITNOT
);
4735 assert( TK_NOT
==OP_Not
); testcase( op
==TK_NOT
);
4736 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4737 testcase( regFree1
==0 );
4738 sqlite3VdbeAddOp2(v
, op
, r1
, inReg
);
4742 int isTrue
; /* IS TRUE or IS NOT TRUE */
4743 int bNormal
; /* IS TRUE or IS FALSE */
4744 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4745 testcase( regFree1
==0 );
4746 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
4747 bNormal
= pExpr
->op2
==TK_IS
;
4748 testcase( isTrue
&& bNormal
);
4749 testcase( !isTrue
&& bNormal
);
4750 sqlite3VdbeAddOp4Int(v
, OP_IsTrue
, r1
, inReg
, !isTrue
, isTrue
^ bNormal
);
4756 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
4757 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
4758 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
4759 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4760 testcase( regFree1
==0 );
4761 addr
= sqlite3VdbeAddOp1(v
, op
, r1
);
4762 VdbeCoverageIf(v
, op
==TK_ISNULL
);
4763 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
4764 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, target
);
4765 sqlite3VdbeJumpHere(v
, addr
);
4768 case TK_AGG_FUNCTION
: {
4769 AggInfo
*pInfo
= pExpr
->pAggInfo
;
4771 || NEVER(pExpr
->iAgg
<0)
4772 || NEVER(pExpr
->iAgg
>=pInfo
->nFunc
)
4774 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4775 sqlite3ErrorMsg(pParse
, "misuse of aggregate: %#T()", pExpr
);
4777 return AggInfoFuncReg(pInfo
, pExpr
->iAgg
);
4782 ExprList
*pFarg
; /* List of function arguments */
4783 int nFarg
; /* Number of function arguments */
4784 FuncDef
*pDef
; /* The function definition object */
4785 const char *zId
; /* The function name */
4786 u32 constMask
= 0; /* Mask of function arguments that are constant */
4787 int i
; /* Loop counter */
4788 sqlite3
*db
= pParse
->db
; /* The database connection */
4789 u8 enc
= ENC(db
); /* The text encoding used by this database */
4790 CollSeq
*pColl
= 0; /* A collating sequence */
4792 #ifndef SQLITE_OMIT_WINDOWFUNC
4793 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
4794 return pExpr
->y
.pWin
->regResult
;
4798 if( ConstFactorOk(pParse
) && sqlite3ExprIsConstantNotJoin(pExpr
) ){
4799 /* SQL functions can be expensive. So try to avoid running them
4800 ** multiple times if we know they always give the same result */
4801 return sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, -1);
4803 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
) );
4804 assert( ExprUseXList(pExpr
) );
4805 pFarg
= pExpr
->x
.pList
;
4806 nFarg
= pFarg
? pFarg
->nExpr
: 0;
4807 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4808 zId
= pExpr
->u
.zToken
;
4809 pDef
= sqlite3FindFunction(db
, zId
, nFarg
, enc
, 0);
4810 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4811 if( pDef
==0 && pParse
->explain
){
4812 pDef
= sqlite3FindFunction(db
, "unknown", nFarg
, enc
, 0);
4815 if( pDef
==0 || pDef
->xFinalize
!=0 ){
4816 sqlite3ErrorMsg(pParse
, "unknown function: %#T()", pExpr
);
4819 if( (pDef
->funcFlags
& SQLITE_FUNC_INLINE
)!=0 && ALWAYS(pFarg
!=0) ){
4820 assert( (pDef
->funcFlags
& SQLITE_FUNC_UNSAFE
)==0 );
4821 assert( (pDef
->funcFlags
& SQLITE_FUNC_DIRECT
)==0 );
4822 return exprCodeInlineFunction(pParse
, pFarg
,
4823 SQLITE_PTR_TO_INT(pDef
->pUserData
), target
);
4824 }else if( pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
) ){
4825 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
4828 for(i
=0; i
<nFarg
; i
++){
4829 if( i
<32 && sqlite3ExprIsConstant(pFarg
->a
[i
].pExpr
) ){
4831 constMask
|= MASKBIT32(i
);
4833 if( (pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
)!=0 && !pColl
){
4834 pColl
= sqlite3ExprCollSeq(pParse
, pFarg
->a
[i
].pExpr
);
4839 r1
= pParse
->nMem
+1;
4840 pParse
->nMem
+= nFarg
;
4842 r1
= sqlite3GetTempRange(pParse
, nFarg
);
4845 /* For length() and typeof() and octet_length() functions,
4846 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4847 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid
4848 ** unnecessary data loading.
4850 if( (pDef
->funcFlags
& (SQLITE_FUNC_LENGTH
|SQLITE_FUNC_TYPEOF
))!=0 ){
4853 assert( pFarg
->a
[0].pExpr
!=0 );
4854 exprOp
= pFarg
->a
[0].pExpr
->op
;
4855 if( exprOp
==TK_COLUMN
|| exprOp
==TK_AGG_COLUMN
){
4856 assert( SQLITE_FUNC_LENGTH
==OPFLAG_LENGTHARG
);
4857 assert( SQLITE_FUNC_TYPEOF
==OPFLAG_TYPEOFARG
);
4858 assert( SQLITE_FUNC_BYTELEN
==OPFLAG_BYTELENARG
);
4859 assert( (OPFLAG_LENGTHARG
|OPFLAG_TYPEOFARG
)==OPFLAG_BYTELENARG
);
4860 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_LENGTHARG
);
4861 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_TYPEOFARG
);
4862 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_BYTELENARG
);
4863 pFarg
->a
[0].pExpr
->op2
= pDef
->funcFlags
& OPFLAG_BYTELENARG
;
4867 sqlite3ExprCodeExprList(pParse
, pFarg
, r1
, 0, SQLITE_ECEL_FACTOR
);
4871 #ifndef SQLITE_OMIT_VIRTUALTABLE
4872 /* Possibly overload the function if the first argument is
4873 ** a virtual table column.
4875 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4876 ** second argument, not the first, as the argument to test to
4877 ** see if it is a column in a virtual table. This is done because
4878 ** the left operand of infix functions (the operand we want to
4879 ** control overloading) ends up as the second argument to the
4880 ** function. The expression "A glob B" is equivalent to
4881 ** "glob(B,A). We want to use the A in "A glob B" to test
4882 ** for function overloading. But we use the B term in "glob(B,A)".
4884 if( nFarg
>=2 && ExprHasProperty(pExpr
, EP_InfixFunc
) ){
4885 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[1].pExpr
);
4886 }else if( nFarg
>0 ){
4887 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[0].pExpr
);
4890 if( pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
){
4891 if( !pColl
) pColl
= db
->pDfltColl
;
4892 sqlite3VdbeAddOp4(v
, OP_CollSeq
, 0, 0, 0, (char *)pColl
, P4_COLLSEQ
);
4894 sqlite3VdbeAddFunctionCall(pParse
, constMask
, r1
, target
, nFarg
,
4898 sqlite3ReleaseTempRange(pParse
, r1
, nFarg
);
4900 sqlite3VdbeReleaseRegisters(pParse
, r1
, nFarg
, constMask
, 1);
4905 #ifndef SQLITE_OMIT_SUBQUERY
4909 testcase( op
==TK_EXISTS
);
4910 testcase( op
==TK_SELECT
);
4911 if( pParse
->db
->mallocFailed
){
4913 }else if( op
==TK_SELECT
4914 && ALWAYS( ExprUseXSelect(pExpr
) )
4915 && (nCol
= pExpr
->x
.pSelect
->pEList
->nExpr
)!=1
4917 sqlite3SubselectError(pParse
, nCol
, 1);
4919 return sqlite3CodeSubselect(pParse
, pExpr
);
4923 case TK_SELECT_COLUMN
: {
4925 Expr
*pLeft
= pExpr
->pLeft
;
4926 if( pLeft
->iTable
==0 || pParse
->withinRJSubrtn
> pLeft
->op2
){
4927 pLeft
->iTable
= sqlite3CodeSubselect(pParse
, pLeft
);
4928 pLeft
->op2
= pParse
->withinRJSubrtn
;
4930 assert( pLeft
->op
==TK_SELECT
|| pLeft
->op
==TK_ERROR
);
4931 n
= sqlite3ExprVectorSize(pLeft
);
4932 if( pExpr
->iTable
!=n
){
4933 sqlite3ErrorMsg(pParse
, "%d columns assigned %d values",
4936 return pLeft
->iTable
+ pExpr
->iColumn
;
4939 int destIfFalse
= sqlite3VdbeMakeLabel(pParse
);
4940 int destIfNull
= sqlite3VdbeMakeLabel(pParse
);
4941 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4942 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
4943 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
4944 sqlite3VdbeResolveLabel(v
, destIfFalse
);
4945 sqlite3VdbeAddOp2(v
, OP_AddImm
, target
, 0);
4946 sqlite3VdbeResolveLabel(v
, destIfNull
);
4949 #endif /* SQLITE_OMIT_SUBQUERY */
4953 ** x BETWEEN y AND z
4955 ** This is equivalent to
4959 ** X is stored in pExpr->pLeft.
4960 ** Y is stored in pExpr->pList->a[0].pExpr.
4961 ** Z is stored in pExpr->pList->a[1].pExpr.
4964 exprCodeBetween(pParse
, pExpr
, target
, 0, 0);
4968 if( !ExprHasProperty(pExpr
, EP_Collate
) ){
4969 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
4970 ** "SOFT-COLLATE" that is added to constraints that are pushed down
4971 ** from outer queries into sub-queries by the push-down optimization.
4972 ** Clear subtypes as subtypes may not cross a subquery boundary.
4974 assert( pExpr
->pLeft
);
4975 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
4976 sqlite3VdbeAddOp1(v
, OP_ClrSubtype
, target
);
4979 pExpr
= pExpr
->pLeft
;
4980 goto expr_code_doover
; /* 2018-04-28: Prevent deep recursion. */
4985 pExpr
= pExpr
->pLeft
;
4986 goto expr_code_doover
; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4990 /* If the opcode is TK_TRIGGER, then the expression is a reference
4991 ** to a column in the new.* or old.* pseudo-tables available to
4992 ** trigger programs. In this case Expr.iTable is set to 1 for the
4993 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4994 ** is set to the column of the pseudo-table to read, or to -1 to
4995 ** read the rowid field.
4997 ** The expression is implemented using an OP_Param opcode. The p1
4998 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4999 ** to reference another column of the old.* pseudo-table, where
5000 ** i is the index of the column. For a new.rowid reference, p1 is
5001 ** set to (n+1), where n is the number of columns in each pseudo-table.
5002 ** For a reference to any other column in the new.* pseudo-table, p1
5003 ** is set to (n+2+i), where n and i are as defined previously. For
5004 ** example, if the table on which triggers are being fired is
5007 ** CREATE TABLE t1(a, b);
5009 ** Then p1 is interpreted as follows:
5011 ** p1==0 -> old.rowid p1==3 -> new.rowid
5012 ** p1==1 -> old.a p1==4 -> new.a
5013 ** p1==2 -> old.b p1==5 -> new.b
5019 assert( ExprUseYTab(pExpr
) );
5020 pTab
= pExpr
->y
.pTab
;
5021 iCol
= pExpr
->iColumn
;
5022 p1
= pExpr
->iTable
* (pTab
->nCol
+1) + 1
5023 + sqlite3TableColumnToStorage(pTab
, iCol
);
5025 assert( pExpr
->iTable
==0 || pExpr
->iTable
==1 );
5026 assert( iCol
>=-1 && iCol
<pTab
->nCol
);
5027 assert( pTab
->iPKey
<0 || iCol
!=pTab
->iPKey
);
5028 assert( p1
>=0 && p1
<(pTab
->nCol
*2+2) );
5030 sqlite3VdbeAddOp2(v
, OP_Param
, p1
, target
);
5031 VdbeComment((v
, "r[%d]=%s.%s", target
,
5032 (pExpr
->iTable
? "new" : "old"),
5033 (pExpr
->iColumn
<0 ? "rowid" : pExpr
->y
.pTab
->aCol
[iCol
].zCnName
)
5036 #ifndef SQLITE_OMIT_FLOATING_POINT
5037 /* If the column has REAL affinity, it may currently be stored as an
5038 ** integer. Use OP_RealAffinity to make sure it is really real.
5040 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
5041 ** floating point when extracting it from the record. */
5042 if( iCol
>=0 && pTab
->aCol
[iCol
].affinity
==SQLITE_AFF_REAL
){
5043 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
5050 sqlite3ErrorMsg(pParse
, "row value misused");
5054 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
5055 ** that derive from the right-hand table of a LEFT JOIN. The
5056 ** Expr.iTable value is the table number for the right-hand table.
5057 ** The expression is only evaluated if that table is not currently
5058 ** on a LEFT JOIN NULL row.
5060 case TK_IF_NULL_ROW
: {
5062 u8 okConstFactor
= pParse
->okConstFactor
;
5063 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
5065 assert( pExpr
->iAgg
>=0 && pExpr
->iAgg
<pAggInfo
->nColumn
);
5066 if( !pAggInfo
->directMode
){
5067 inReg
= AggInfoColumnReg(pAggInfo
, pExpr
->iAgg
);
5070 if( pExpr
->pAggInfo
->useSortingIdx
){
5071 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
5072 pAggInfo
->aCol
[pExpr
->iAgg
].iSorterColumn
,
5078 addrINR
= sqlite3VdbeAddOp3(v
, OP_IfNullRow
, pExpr
->iTable
, 0, target
);
5079 /* The OP_IfNullRow opcode above can overwrite the result register with
5080 ** NULL. So we have to ensure that the result register is not a value
5081 ** that is suppose to be a constant. Two defenses are needed:
5082 ** (1) Temporarily disable factoring of constant expressions
5083 ** (2) Make sure the computed value really is stored in register
5084 ** "target" and not someplace else.
5086 pParse
->okConstFactor
= 0; /* note (1) above */
5087 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
5088 assert( target
==inReg
);
5089 pParse
->okConstFactor
= okConstFactor
;
5090 sqlite3VdbeJumpHere(v
, addrINR
);
5096 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5099 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5101 ** Form A is can be transformed into the equivalent form B as follows:
5102 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
5103 ** WHEN x=eN THEN rN ELSE y END
5105 ** X (if it exists) is in pExpr->pLeft.
5106 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
5107 ** odd. The Y is also optional. If the number of elements in x.pList
5108 ** is even, then Y is omitted and the "otherwise" result is NULL.
5109 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
5111 ** The result of the expression is the Ri for the first matching Ei,
5112 ** or if there is no matching Ei, the ELSE term Y, or if there is
5113 ** no ELSE term, NULL.
5116 int endLabel
; /* GOTO label for end of CASE stmt */
5117 int nextCase
; /* GOTO label for next WHEN clause */
5118 int nExpr
; /* 2x number of WHEN terms */
5119 int i
; /* Loop counter */
5120 ExprList
*pEList
; /* List of WHEN terms */
5121 struct ExprList_item
*aListelem
; /* Array of WHEN terms */
5122 Expr opCompare
; /* The X==Ei expression */
5123 Expr
*pX
; /* The X expression */
5124 Expr
*pTest
= 0; /* X==Ei (form A) or just Ei (form B) */
5126 sqlite3
*db
= pParse
->db
;
5128 assert( ExprUseXList(pExpr
) && pExpr
->x
.pList
!=0 );
5129 assert(pExpr
->x
.pList
->nExpr
> 0);
5130 pEList
= pExpr
->x
.pList
;
5131 aListelem
= pEList
->a
;
5132 nExpr
= pEList
->nExpr
;
5133 endLabel
= sqlite3VdbeMakeLabel(pParse
);
5134 if( (pX
= pExpr
->pLeft
)!=0 ){
5135 pDel
= sqlite3ExprDup(db
, pX
, 0);
5136 if( db
->mallocFailed
){
5137 sqlite3ExprDelete(db
, pDel
);
5140 testcase( pX
->op
==TK_COLUMN
);
5141 exprToRegister(pDel
, exprCodeVector(pParse
, pDel
, ®Free1
));
5142 testcase( regFree1
==0 );
5143 memset(&opCompare
, 0, sizeof(opCompare
));
5144 opCompare
.op
= TK_EQ
;
5145 opCompare
.pLeft
= pDel
;
5147 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
5148 ** The value in regFree1 might get SCopy-ed into the file result.
5149 ** So make sure that the regFree1 register is not reused for other
5150 ** purposes and possibly overwritten. */
5153 for(i
=0; i
<nExpr
-1; i
=i
+2){
5156 opCompare
.pRight
= aListelem
[i
].pExpr
;
5158 pTest
= aListelem
[i
].pExpr
;
5160 nextCase
= sqlite3VdbeMakeLabel(pParse
);
5161 testcase( pTest
->op
==TK_COLUMN
);
5162 sqlite3ExprIfFalse(pParse
, pTest
, nextCase
, SQLITE_JUMPIFNULL
);
5163 testcase( aListelem
[i
+1].pExpr
->op
==TK_COLUMN
);
5164 sqlite3ExprCode(pParse
, aListelem
[i
+1].pExpr
, target
);
5165 sqlite3VdbeGoto(v
, endLabel
);
5166 sqlite3VdbeResolveLabel(v
, nextCase
);
5169 sqlite3ExprCode(pParse
, pEList
->a
[nExpr
-1].pExpr
, target
);
5171 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
5173 sqlite3ExprDelete(db
, pDel
);
5174 setDoNotMergeFlagOnCopy(v
);
5175 sqlite3VdbeResolveLabel(v
, endLabel
);
5178 #ifndef SQLITE_OMIT_TRIGGER
5180 assert( pExpr
->affExpr
==OE_Rollback
5181 || pExpr
->affExpr
==OE_Abort
5182 || pExpr
->affExpr
==OE_Fail
5183 || pExpr
->affExpr
==OE_Ignore
5185 if( !pParse
->pTriggerTab
&& !pParse
->nested
){
5186 sqlite3ErrorMsg(pParse
,
5187 "RAISE() may only be used within a trigger-program");
5190 if( pExpr
->affExpr
==OE_Abort
){
5191 sqlite3MayAbort(pParse
);
5193 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
5194 if( pExpr
->affExpr
==OE_Ignore
){
5196 v
, OP_Halt
, SQLITE_OK
, OE_Ignore
, 0, pExpr
->u
.zToken
,0);
5199 sqlite3HaltConstraint(pParse
,
5200 pParse
->pTriggerTab
? SQLITE_CONSTRAINT_TRIGGER
: SQLITE_ERROR
,
5201 pExpr
->affExpr
, pExpr
->u
.zToken
, 0, 0);
5208 sqlite3ReleaseTempReg(pParse
, regFree1
);
5209 sqlite3ReleaseTempReg(pParse
, regFree2
);
5214 ** Generate code that will evaluate expression pExpr just one time
5215 ** per prepared statement execution.
5217 ** If the expression uses functions (that might throw an exception) then
5218 ** guard them with an OP_Once opcode to ensure that the code is only executed
5219 ** once. If no functions are involved, then factor the code out and put it at
5220 ** the end of the prepared statement in the initialization section.
5222 ** If regDest>0 then the result is always stored in that register and the
5223 ** result is not reusable. If regDest<0 then this routine is free to
5224 ** store the value wherever it wants. The register where the expression
5225 ** is stored is returned. When regDest<0, two identical expressions might
5226 ** code to the same register, if they do not contain function calls and hence
5227 ** are factored out into the initialization section at the end of the
5228 ** prepared statement.
5230 int sqlite3ExprCodeRunJustOnce(
5231 Parse
*pParse
, /* Parsing context */
5232 Expr
*pExpr
, /* The expression to code when the VDBE initializes */
5233 int regDest
/* Store the value in this register */
5236 assert( ConstFactorOk(pParse
) );
5237 assert( regDest
!=0 );
5238 p
= pParse
->pConstExpr
;
5239 if( regDest
<0 && p
){
5240 struct ExprList_item
*pItem
;
5242 for(pItem
=p
->a
, i
=p
->nExpr
; i
>0; pItem
++, i
--){
5243 if( pItem
->fg
.reusable
5244 && sqlite3ExprCompare(0,pItem
->pExpr
,pExpr
,-1)==0
5246 return pItem
->u
.iConstExprReg
;
5250 pExpr
= sqlite3ExprDup(pParse
->db
, pExpr
, 0);
5251 if( pExpr
!=0 && ExprHasProperty(pExpr
, EP_HasFunc
) ){
5252 Vdbe
*v
= pParse
->pVdbe
;
5255 addr
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
5256 pParse
->okConstFactor
= 0;
5257 if( !pParse
->db
->mallocFailed
){
5258 if( regDest
<0 ) regDest
= ++pParse
->nMem
;
5259 sqlite3ExprCode(pParse
, pExpr
, regDest
);
5261 pParse
->okConstFactor
= 1;
5262 sqlite3ExprDelete(pParse
->db
, pExpr
);
5263 sqlite3VdbeJumpHere(v
, addr
);
5265 p
= sqlite3ExprListAppend(pParse
, p
, pExpr
);
5267 struct ExprList_item
*pItem
= &p
->a
[p
->nExpr
-1];
5268 pItem
->fg
.reusable
= regDest
<0;
5269 if( regDest
<0 ) regDest
= ++pParse
->nMem
;
5270 pItem
->u
.iConstExprReg
= regDest
;
5272 pParse
->pConstExpr
= p
;
5278 ** Generate code to evaluate an expression and store the results
5279 ** into a register. Return the register number where the results
5282 ** If the register is a temporary register that can be deallocated,
5283 ** then write its number into *pReg. If the result register is not
5284 ** a temporary, then set *pReg to zero.
5286 ** If pExpr is a constant, then this routine might generate this
5287 ** code to fill the register in the initialization section of the
5288 ** VDBE program, in order to factor it out of the evaluation loop.
5290 int sqlite3ExprCodeTemp(Parse
*pParse
, Expr
*pExpr
, int *pReg
){
5292 pExpr
= sqlite3ExprSkipCollateAndLikely(pExpr
);
5293 if( ConstFactorOk(pParse
)
5295 && pExpr
->op
!=TK_REGISTER
5296 && sqlite3ExprIsConstantNotJoin(pExpr
)
5299 r2
= sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, -1);
5301 int r1
= sqlite3GetTempReg(pParse
);
5302 r2
= sqlite3ExprCodeTarget(pParse
, pExpr
, r1
);
5306 sqlite3ReleaseTempReg(pParse
, r1
);
5314 ** Generate code that will evaluate expression pExpr and store the
5315 ** results in register target. The results are guaranteed to appear
5316 ** in register target.
5318 void sqlite3ExprCode(Parse
*pParse
, Expr
*pExpr
, int target
){
5321 assert( pExpr
==0 || !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
5322 assert( target
>0 && target
<=pParse
->nMem
);
5323 assert( pParse
->pVdbe
!=0 || pParse
->db
->mallocFailed
);
5324 if( pParse
->pVdbe
==0 ) return;
5325 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
);
5326 if( inReg
!=target
){
5328 Expr
*pX
= sqlite3ExprSkipCollateAndLikely(pExpr
);
5329 testcase( pX
!=pExpr
);
5331 && (ExprHasProperty(pX
,EP_Subquery
) || pX
->op
==TK_REGISTER
)
5337 sqlite3VdbeAddOp2(pParse
->pVdbe
, op
, inReg
, target
);
5342 ** Make a transient copy of expression pExpr and then code it using
5343 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5344 ** except that the input expression is guaranteed to be unchanged.
5346 void sqlite3ExprCodeCopy(Parse
*pParse
, Expr
*pExpr
, int target
){
5347 sqlite3
*db
= pParse
->db
;
5348 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
5349 if( !db
->mallocFailed
) sqlite3ExprCode(pParse
, pExpr
, target
);
5350 sqlite3ExprDelete(db
, pExpr
);
5354 ** Generate code that will evaluate expression pExpr and store the
5355 ** results in register target. The results are guaranteed to appear
5356 ** in register target. If the expression is constant, then this routine
5357 ** might choose to code the expression at initialization time.
5359 void sqlite3ExprCodeFactorable(Parse
*pParse
, Expr
*pExpr
, int target
){
5360 if( pParse
->okConstFactor
&& sqlite3ExprIsConstantNotJoin(pExpr
) ){
5361 sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, target
);
5363 sqlite3ExprCodeCopy(pParse
, pExpr
, target
);
5368 ** Generate code that pushes the value of every element of the given
5369 ** expression list into a sequence of registers beginning at target.
5371 ** Return the number of elements evaluated. The number returned will
5372 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5375 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5376 ** filled using OP_SCopy. OP_Copy must be used instead.
5378 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5379 ** factored out into initialization code.
5381 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5382 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5383 ** in registers at srcReg, and so the value can be copied from there.
5384 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5385 ** are simply omitted rather than being copied from srcReg.
5387 int sqlite3ExprCodeExprList(
5388 Parse
*pParse
, /* Parsing context */
5389 ExprList
*pList
, /* The expression list to be coded */
5390 int target
, /* Where to write results */
5391 int srcReg
, /* Source registers if SQLITE_ECEL_REF */
5392 u8 flags
/* SQLITE_ECEL_* flags */
5394 struct ExprList_item
*pItem
;
5396 u8 copyOp
= (flags
& SQLITE_ECEL_DUP
) ? OP_Copy
: OP_SCopy
;
5397 Vdbe
*v
= pParse
->pVdbe
;
5400 assert( pParse
->pVdbe
!=0 ); /* Never gets this far otherwise */
5402 if( !ConstFactorOk(pParse
) ) flags
&= ~SQLITE_ECEL_FACTOR
;
5403 for(pItem
=pList
->a
, i
=0; i
<n
; i
++, pItem
++){
5404 Expr
*pExpr
= pItem
->pExpr
;
5405 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5406 if( pItem
->fg
.bSorterRef
){
5411 if( (flags
& SQLITE_ECEL_REF
)!=0 && (j
= pItem
->u
.x
.iOrderByCol
)>0 ){
5412 if( flags
& SQLITE_ECEL_OMITREF
){
5416 sqlite3VdbeAddOp2(v
, copyOp
, j
+srcReg
-1, target
+i
);
5418 }else if( (flags
& SQLITE_ECEL_FACTOR
)!=0
5419 && sqlite3ExprIsConstantNotJoin(pExpr
)
5421 sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, target
+i
);
5423 int inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
+i
);
5424 if( inReg
!=target
+i
){
5427 && (pOp
=sqlite3VdbeGetLastOp(v
))->opcode
==OP_Copy
5428 && pOp
->p1
+pOp
->p3
+1==inReg
5429 && pOp
->p2
+pOp
->p3
+1==target
+i
5430 && pOp
->p5
==0 /* The do-not-merge flag must be clear */
5434 sqlite3VdbeAddOp2(v
, copyOp
, inReg
, target
+i
);
5443 ** Generate code for a BETWEEN operator.
5445 ** x BETWEEN y AND z
5447 ** The above is equivalent to
5451 ** Code it as such, taking care to do the common subexpression
5452 ** elimination of x.
5454 ** The xJumpIf parameter determines details:
5456 ** NULL: Store the boolean result in reg[dest]
5457 ** sqlite3ExprIfTrue: Jump to dest if true
5458 ** sqlite3ExprIfFalse: Jump to dest if false
5460 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5462 static void exprCodeBetween(
5463 Parse
*pParse
, /* Parsing and code generating context */
5464 Expr
*pExpr
, /* The BETWEEN expression */
5465 int dest
, /* Jump destination or storage location */
5466 void (*xJump
)(Parse
*,Expr
*,int,int), /* Action to take */
5467 int jumpIfNull
/* Take the jump if the BETWEEN is NULL */
5469 Expr exprAnd
; /* The AND operator in x>=y AND x<=z */
5470 Expr compLeft
; /* The x>=y term */
5471 Expr compRight
; /* The x<=z term */
5472 int regFree1
= 0; /* Temporary use register */
5474 sqlite3
*db
= pParse
->db
;
5476 memset(&compLeft
, 0, sizeof(Expr
));
5477 memset(&compRight
, 0, sizeof(Expr
));
5478 memset(&exprAnd
, 0, sizeof(Expr
));
5480 assert( ExprUseXList(pExpr
) );
5481 pDel
= sqlite3ExprDup(db
, pExpr
->pLeft
, 0);
5482 if( db
->mallocFailed
==0 ){
5483 exprAnd
.op
= TK_AND
;
5484 exprAnd
.pLeft
= &compLeft
;
5485 exprAnd
.pRight
= &compRight
;
5486 compLeft
.op
= TK_GE
;
5487 compLeft
.pLeft
= pDel
;
5488 compLeft
.pRight
= pExpr
->x
.pList
->a
[0].pExpr
;
5489 compRight
.op
= TK_LE
;
5490 compRight
.pLeft
= pDel
;
5491 compRight
.pRight
= pExpr
->x
.pList
->a
[1].pExpr
;
5492 exprToRegister(pDel
, exprCodeVector(pParse
, pDel
, ®Free1
));
5494 xJump(pParse
, &exprAnd
, dest
, jumpIfNull
);
5496 /* Mark the expression is being from the ON or USING clause of a join
5497 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5498 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5499 ** for clarity, but we are out of bits in the Expr.flags field so we
5500 ** have to reuse the EP_OuterON bit. Bummer. */
5501 pDel
->flags
|= EP_OuterON
;
5502 sqlite3ExprCodeTarget(pParse
, &exprAnd
, dest
);
5504 sqlite3ReleaseTempReg(pParse
, regFree1
);
5506 sqlite3ExprDelete(db
, pDel
);
5508 /* Ensure adequate test coverage */
5509 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
==0 && regFree1
==0 );
5510 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
==0 && regFree1
!=0 );
5511 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
!=0 && regFree1
==0 );
5512 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
!=0 && regFree1
!=0 );
5513 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
==0 && regFree1
==0 );
5514 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
==0 && regFree1
!=0 );
5515 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
!=0 && regFree1
==0 );
5516 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
!=0 && regFree1
!=0 );
5517 testcase( xJump
==0 );
5521 ** Generate code for a boolean expression such that a jump is made
5522 ** to the label "dest" if the expression is true but execution
5523 ** continues straight thru if the expression is false.
5525 ** If the expression evaluates to NULL (neither true nor false), then
5526 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5528 ** This code depends on the fact that certain token values (ex: TK_EQ)
5529 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5530 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5531 ** the make process cause these values to align. Assert()s in the code
5532 ** below verify that the numbers are aligned correctly.
5534 void sqlite3ExprIfTrue(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
5535 Vdbe
*v
= pParse
->pVdbe
;
5541 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
5542 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
5543 if( NEVER(pExpr
==0) ) return; /* No way this can happen */
5544 assert( !ExprHasVVAProperty(pExpr
, EP_Immutable
) );
5549 Expr
*pAlt
= sqlite3ExprSimplifiedAndOr(pExpr
);
5551 sqlite3ExprIfTrue(pParse
, pAlt
, dest
, jumpIfNull
);
5552 }else if( op
==TK_AND
){
5553 int d2
= sqlite3VdbeMakeLabel(pParse
);
5554 testcase( jumpIfNull
==0 );
5555 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, d2
,
5556 jumpIfNull
^SQLITE_JUMPIFNULL
);
5557 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5558 sqlite3VdbeResolveLabel(v
, d2
);
5560 testcase( jumpIfNull
==0 );
5561 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5562 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5567 testcase( jumpIfNull
==0 );
5568 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5572 int isNot
; /* IS NOT TRUE or IS NOT FALSE */
5573 int isTrue
; /* IS TRUE or IS NOT TRUE */
5574 testcase( jumpIfNull
==0 );
5575 isNot
= pExpr
->op2
==TK_ISNOT
;
5576 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
5577 testcase( isTrue
&& isNot
);
5578 testcase( !isTrue
&& isNot
);
5579 if( isTrue
^ isNot
){
5580 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
,
5581 isNot
? SQLITE_JUMPIFNULL
: 0);
5583 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
,
5584 isNot
? SQLITE_JUMPIFNULL
: 0);
5590 testcase( op
==TK_IS
);
5591 testcase( op
==TK_ISNOT
);
5592 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
5593 jumpIfNull
= SQLITE_NULLEQ
;
5594 /* no break */ deliberate_fall_through
5601 if( sqlite3ExprIsVector(pExpr
->pLeft
) ) goto default_expr
;
5602 testcase( jumpIfNull
==0 );
5603 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5604 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
5605 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
5606 r1
, r2
, dest
, jumpIfNull
, ExprHasProperty(pExpr
,EP_Commuted
));
5607 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
5608 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
5609 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
5610 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
5611 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
);
5612 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
==SQLITE_NULLEQ
);
5613 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
!=SQLITE_NULLEQ
);
5614 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
);
5615 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
==SQLITE_NULLEQ
);
5616 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
!=SQLITE_NULLEQ
);
5617 testcase( regFree1
==0 );
5618 testcase( regFree2
==0 );
5623 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
5624 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
5625 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5626 sqlite3VdbeTypeofColumn(v
, r1
);
5627 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
5628 VdbeCoverageIf(v
, op
==TK_ISNULL
);
5629 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
5630 testcase( regFree1
==0 );
5634 testcase( jumpIfNull
==0 );
5635 exprCodeBetween(pParse
, pExpr
, dest
, sqlite3ExprIfTrue
, jumpIfNull
);
5638 #ifndef SQLITE_OMIT_SUBQUERY
5640 int destIfFalse
= sqlite3VdbeMakeLabel(pParse
);
5641 int destIfNull
= jumpIfNull
? dest
: destIfFalse
;
5642 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
5643 sqlite3VdbeGoto(v
, dest
);
5644 sqlite3VdbeResolveLabel(v
, destIfFalse
);
5650 if( ExprAlwaysTrue(pExpr
) ){
5651 sqlite3VdbeGoto(v
, dest
);
5652 }else if( ExprAlwaysFalse(pExpr
) ){
5655 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
5656 sqlite3VdbeAddOp3(v
, OP_If
, r1
, dest
, jumpIfNull
!=0);
5658 testcase( regFree1
==0 );
5659 testcase( jumpIfNull
==0 );
5664 sqlite3ReleaseTempReg(pParse
, regFree1
);
5665 sqlite3ReleaseTempReg(pParse
, regFree2
);
5669 ** Generate code for a boolean expression such that a jump is made
5670 ** to the label "dest" if the expression is false but execution
5671 ** continues straight thru if the expression is true.
5673 ** If the expression evaluates to NULL (neither true nor false) then
5674 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5677 void sqlite3ExprIfFalse(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
5678 Vdbe
*v
= pParse
->pVdbe
;
5684 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
5685 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
5686 if( pExpr
==0 ) return;
5687 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
5689 /* The value of pExpr->op and op are related as follows:
5692 ** --------- ----------
5693 ** TK_ISNULL OP_NotNull
5694 ** TK_NOTNULL OP_IsNull
5702 ** For other values of pExpr->op, op is undefined and unused.
5703 ** The value of TK_ and OP_ constants are arranged such that we
5704 ** can compute the mapping above using the following expression.
5705 ** Assert()s verify that the computation is correct.
5707 op
= ((pExpr
->op
+(TK_ISNULL
&1))^1)-(TK_ISNULL
&1);
5709 /* Verify correct alignment of TK_ and OP_ constants
5711 assert( pExpr
->op
!=TK_ISNULL
|| op
==OP_NotNull
);
5712 assert( pExpr
->op
!=TK_NOTNULL
|| op
==OP_IsNull
);
5713 assert( pExpr
->op
!=TK_NE
|| op
==OP_Eq
);
5714 assert( pExpr
->op
!=TK_EQ
|| op
==OP_Ne
);
5715 assert( pExpr
->op
!=TK_LT
|| op
==OP_Ge
);
5716 assert( pExpr
->op
!=TK_LE
|| op
==OP_Gt
);
5717 assert( pExpr
->op
!=TK_GT
|| op
==OP_Le
);
5718 assert( pExpr
->op
!=TK_GE
|| op
==OP_Lt
);
5720 switch( pExpr
->op
){
5723 Expr
*pAlt
= sqlite3ExprSimplifiedAndOr(pExpr
);
5725 sqlite3ExprIfFalse(pParse
, pAlt
, dest
, jumpIfNull
);
5726 }else if( pExpr
->op
==TK_AND
){
5727 testcase( jumpIfNull
==0 );
5728 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5729 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5731 int d2
= sqlite3VdbeMakeLabel(pParse
);
5732 testcase( jumpIfNull
==0 );
5733 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, d2
,
5734 jumpIfNull
^SQLITE_JUMPIFNULL
);
5735 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5736 sqlite3VdbeResolveLabel(v
, d2
);
5741 testcase( jumpIfNull
==0 );
5742 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5746 int isNot
; /* IS NOT TRUE or IS NOT FALSE */
5747 int isTrue
; /* IS TRUE or IS NOT TRUE */
5748 testcase( jumpIfNull
==0 );
5749 isNot
= pExpr
->op2
==TK_ISNOT
;
5750 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
5751 testcase( isTrue
&& isNot
);
5752 testcase( !isTrue
&& isNot
);
5753 if( isTrue
^ isNot
){
5754 /* IS TRUE and IS NOT FALSE */
5755 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
,
5756 isNot
? 0 : SQLITE_JUMPIFNULL
);
5759 /* IS FALSE and IS NOT TRUE */
5760 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
,
5761 isNot
? 0 : SQLITE_JUMPIFNULL
);
5767 testcase( pExpr
->op
==TK_IS
);
5768 testcase( pExpr
->op
==TK_ISNOT
);
5769 op
= (pExpr
->op
==TK_IS
) ? TK_NE
: TK_EQ
;
5770 jumpIfNull
= SQLITE_NULLEQ
;
5771 /* no break */ deliberate_fall_through
5778 if( sqlite3ExprIsVector(pExpr
->pLeft
) ) goto default_expr
;
5779 testcase( jumpIfNull
==0 );
5780 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5781 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
5782 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
5783 r1
, r2
, dest
, jumpIfNull
,ExprHasProperty(pExpr
,EP_Commuted
));
5784 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
5785 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
5786 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
5787 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
5788 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
);
5789 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
!=SQLITE_NULLEQ
);
5790 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
==SQLITE_NULLEQ
);
5791 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
);
5792 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
!=SQLITE_NULLEQ
);
5793 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
==SQLITE_NULLEQ
);
5794 testcase( regFree1
==0 );
5795 testcase( regFree2
==0 );
5800 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5801 sqlite3VdbeTypeofColumn(v
, r1
);
5802 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
5803 testcase( op
==TK_ISNULL
); VdbeCoverageIf(v
, op
==TK_ISNULL
);
5804 testcase( op
==TK_NOTNULL
); VdbeCoverageIf(v
, op
==TK_NOTNULL
);
5805 testcase( regFree1
==0 );
5809 testcase( jumpIfNull
==0 );
5810 exprCodeBetween(pParse
, pExpr
, dest
, sqlite3ExprIfFalse
, jumpIfNull
);
5813 #ifndef SQLITE_OMIT_SUBQUERY
5816 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, dest
);
5818 int destIfNull
= sqlite3VdbeMakeLabel(pParse
);
5819 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, destIfNull
);
5820 sqlite3VdbeResolveLabel(v
, destIfNull
);
5827 if( ExprAlwaysFalse(pExpr
) ){
5828 sqlite3VdbeGoto(v
, dest
);
5829 }else if( ExprAlwaysTrue(pExpr
) ){
5832 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
5833 sqlite3VdbeAddOp3(v
, OP_IfNot
, r1
, dest
, jumpIfNull
!=0);
5835 testcase( regFree1
==0 );
5836 testcase( jumpIfNull
==0 );
5841 sqlite3ReleaseTempReg(pParse
, regFree1
);
5842 sqlite3ReleaseTempReg(pParse
, regFree2
);
5846 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5847 ** code generation, and that copy is deleted after code generation. This
5848 ** ensures that the original pExpr is unchanged.
5850 void sqlite3ExprIfFalseDup(Parse
*pParse
, Expr
*pExpr
, int dest
,int jumpIfNull
){
5851 sqlite3
*db
= pParse
->db
;
5852 Expr
*pCopy
= sqlite3ExprDup(db
, pExpr
, 0);
5853 if( db
->mallocFailed
==0 ){
5854 sqlite3ExprIfFalse(pParse
, pCopy
, dest
, jumpIfNull
);
5856 sqlite3ExprDelete(db
, pCopy
);
5860 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5861 ** type of expression.
5863 ** If pExpr is a simple SQL value - an integer, real, string, blob
5864 ** or NULL value - then the VDBE currently being prepared is configured
5865 ** to re-prepare each time a new value is bound to variable pVar.
5867 ** Additionally, if pExpr is a simple SQL value and the value is the
5868 ** same as that currently bound to variable pVar, non-zero is returned.
5869 ** Otherwise, if the values are not the same or if pExpr is not a simple
5870 ** SQL value, zero is returned.
5872 static int exprCompareVariable(
5873 const Parse
*pParse
,
5879 sqlite3_value
*pL
, *pR
= 0;
5881 sqlite3ValueFromExpr(pParse
->db
, pExpr
, SQLITE_UTF8
, SQLITE_AFF_BLOB
, &pR
);
5883 iVar
= pVar
->iColumn
;
5884 sqlite3VdbeSetVarmask(pParse
->pVdbe
, iVar
);
5885 pL
= sqlite3VdbeGetBoundValue(pParse
->pReprepare
, iVar
, SQLITE_AFF_BLOB
);
5887 if( sqlite3_value_type(pL
)==SQLITE_TEXT
){
5888 sqlite3_value_text(pL
); /* Make sure the encoding is UTF-8 */
5890 res
= 0==sqlite3MemCompare(pL
, pR
, 0);
5892 sqlite3ValueFree(pR
);
5893 sqlite3ValueFree(pL
);
5900 ** Do a deep comparison of two expression trees. Return 0 if the two
5901 ** expressions are completely identical. Return 1 if they differ only
5902 ** by a COLLATE operator at the top level. Return 2 if there are differences
5903 ** other than the top-level COLLATE operator.
5905 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5906 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5908 ** The pA side might be using TK_REGISTER. If that is the case and pB is
5909 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5911 ** Sometimes this routine will return 2 even if the two expressions
5912 ** really are equivalent. If we cannot prove that the expressions are
5913 ** identical, we return 2 just to be safe. So if this routine
5914 ** returns 2, then you do not really know for certain if the two
5915 ** expressions are the same. But if you get a 0 or 1 return, then you
5916 ** can be sure the expressions are the same. In the places where
5917 ** this routine is used, it does not hurt to get an extra 2 - that
5918 ** just might result in some slightly slower code. But returning
5919 ** an incorrect 0 or 1 could lead to a malfunction.
5921 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5922 ** pParse->pReprepare can be matched against literals in pB. The
5923 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5924 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5925 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5926 ** pB causes a return value of 2.
5928 int sqlite3ExprCompare(
5929 const Parse
*pParse
,
5935 if( pA
==0 || pB
==0 ){
5936 return pB
==pA
? 0 : 2;
5938 if( pParse
&& pA
->op
==TK_VARIABLE
&& exprCompareVariable(pParse
, pA
, pB
) ){
5941 combinedFlags
= pA
->flags
| pB
->flags
;
5942 if( combinedFlags
& EP_IntValue
){
5943 if( (pA
->flags
&pB
->flags
&EP_IntValue
)!=0 && pA
->u
.iValue
==pB
->u
.iValue
){
5948 if( pA
->op
!=pB
->op
|| pA
->op
==TK_RAISE
){
5949 if( pA
->op
==TK_COLLATE
&& sqlite3ExprCompare(pParse
, pA
->pLeft
,pB
,iTab
)<2 ){
5952 if( pB
->op
==TK_COLLATE
&& sqlite3ExprCompare(pParse
, pA
,pB
->pLeft
,iTab
)<2 ){
5955 if( pA
->op
==TK_AGG_COLUMN
&& pB
->op
==TK_COLUMN
5956 && pB
->iTable
<0 && pA
->iTable
==iTab
5963 assert( !ExprHasProperty(pA
, EP_IntValue
) );
5964 assert( !ExprHasProperty(pB
, EP_IntValue
) );
5966 if( pA
->op
==TK_FUNCTION
|| pA
->op
==TK_AGG_FUNCTION
){
5967 if( sqlite3StrICmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ) return 2;
5968 #ifndef SQLITE_OMIT_WINDOWFUNC
5969 assert( pA
->op
==pB
->op
);
5970 if( ExprHasProperty(pA
,EP_WinFunc
)!=ExprHasProperty(pB
,EP_WinFunc
) ){
5973 if( ExprHasProperty(pA
,EP_WinFunc
) ){
5974 if( sqlite3WindowCompare(pParse
, pA
->y
.pWin
, pB
->y
.pWin
, 1)!=0 ){
5979 }else if( pA
->op
==TK_NULL
){
5981 }else if( pA
->op
==TK_COLLATE
){
5982 if( sqlite3_stricmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ) return 2;
5985 && pA
->op
!=TK_COLUMN
5986 && pA
->op
!=TK_AGG_COLUMN
5987 && strcmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0
5992 if( (pA
->flags
& (EP_Distinct
|EP_Commuted
))
5993 != (pB
->flags
& (EP_Distinct
|EP_Commuted
)) ) return 2;
5994 if( ALWAYS((combinedFlags
& EP_TokenOnly
)==0) ){
5995 if( combinedFlags
& EP_xIsSelect
) return 2;
5996 if( (combinedFlags
& EP_FixedCol
)==0
5997 && sqlite3ExprCompare(pParse
, pA
->pLeft
, pB
->pLeft
, iTab
) ) return 2;
5998 if( sqlite3ExprCompare(pParse
, pA
->pRight
, pB
->pRight
, iTab
) ) return 2;
5999 if( sqlite3ExprListCompare(pA
->x
.pList
, pB
->x
.pList
, iTab
) ) return 2;
6000 if( pA
->op
!=TK_STRING
6001 && pA
->op
!=TK_TRUEFALSE
6002 && ALWAYS((combinedFlags
& EP_Reduced
)==0)
6004 if( pA
->iColumn
!=pB
->iColumn
) return 2;
6005 if( pA
->op2
!=pB
->op2
&& pA
->op
==TK_TRUTH
) return 2;
6006 if( pA
->op
!=TK_IN
&& pA
->iTable
!=pB
->iTable
&& pA
->iTable
!=iTab
){
6015 ** Compare two ExprList objects. Return 0 if they are identical, 1
6016 ** if they are certainly different, or 2 if it is not possible to
6017 ** determine if they are identical or not.
6019 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6020 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6022 ** This routine might return non-zero for equivalent ExprLists. The
6023 ** only consequence will be disabled optimizations. But this routine
6024 ** must never return 0 if the two ExprList objects are different, or
6025 ** a malfunction will result.
6027 ** Two NULL pointers are considered to be the same. But a NULL pointer
6028 ** always differs from a non-NULL pointer.
6030 int sqlite3ExprListCompare(const ExprList
*pA
, const ExprList
*pB
, int iTab
){
6032 if( pA
==0 && pB
==0 ) return 0;
6033 if( pA
==0 || pB
==0 ) return 1;
6034 if( pA
->nExpr
!=pB
->nExpr
) return 1;
6035 for(i
=0; i
<pA
->nExpr
; i
++){
6037 Expr
*pExprA
= pA
->a
[i
].pExpr
;
6038 Expr
*pExprB
= pB
->a
[i
].pExpr
;
6039 if( pA
->a
[i
].fg
.sortFlags
!=pB
->a
[i
].fg
.sortFlags
) return 1;
6040 if( (res
= sqlite3ExprCompare(0, pExprA
, pExprB
, iTab
)) ) return res
;
6046 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
6049 int sqlite3ExprCompareSkip(Expr
*pA
,Expr
*pB
, int iTab
){
6050 return sqlite3ExprCompare(0,
6051 sqlite3ExprSkipCollate(pA
),
6052 sqlite3ExprSkipCollate(pB
),
6057 ** Return non-zero if Expr p can only be true if pNN is not NULL.
6059 ** Or if seenNot is true, return non-zero if Expr p can only be
6060 ** non-NULL if pNN is not NULL
6062 static int exprImpliesNotNull(
6063 const Parse
*pParse
,/* Parsing context */
6064 const Expr
*p
, /* The expression to be checked */
6065 const Expr
*pNN
, /* The expression that is NOT NULL */
6066 int iTab
, /* Table being evaluated */
6067 int seenNot
/* Return true only if p can be any non-NULL value */
6071 if( sqlite3ExprCompare(pParse
, p
, pNN
, iTab
)==0 ){
6072 return pNN
->op
!=TK_NULL
;
6076 if( seenNot
&& ExprHasProperty(p
, EP_xIsSelect
) ) return 0;
6077 assert( ExprUseXSelect(p
) || (p
->x
.pList
!=0 && p
->x
.pList
->nExpr
>0) );
6078 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6082 assert( ExprUseXList(p
) );
6085 assert( pList
->nExpr
==2 );
6086 if( seenNot
) return 0;
6087 if( exprImpliesNotNull(pParse
, pList
->a
[0].pExpr
, pNN
, iTab
, 1)
6088 || exprImpliesNotNull(pParse
, pList
->a
[1].pExpr
, pNN
, iTab
, 1)
6092 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6107 /* no break */ deliberate_fall_through
6112 if( exprImpliesNotNull(pParse
, p
->pRight
, pNN
, iTab
, seenNot
) ) return 1;
6113 /* no break */ deliberate_fall_through
6119 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, seenNot
);
6122 if( seenNot
) return 0;
6123 if( p
->op2
!=TK_IS
) return 0;
6124 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6128 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6135 ** Return true if we can prove the pE2 will always be true if pE1 is
6136 ** true. Return false if we cannot complete the proof or if pE2 might
6137 ** be false. Examples:
6139 ** pE1: x==5 pE2: x==5 Result: true
6140 ** pE1: x>0 pE2: x==5 Result: false
6141 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
6142 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
6143 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
6144 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
6145 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false
6147 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
6148 ** Expr.iTable<0 then assume a table number given by iTab.
6150 ** If pParse is not NULL, then the values of bound variables in pE1 are
6151 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
6152 ** modified to record which bound variables are referenced. If pParse
6153 ** is NULL, then false will be returned if pE1 contains any bound variables.
6155 ** When in doubt, return false. Returning true might give a performance
6156 ** improvement. Returning false might cause a performance reduction, but
6157 ** it will always give the correct answer and is hence always safe.
6159 int sqlite3ExprImpliesExpr(
6160 const Parse
*pParse
,
6165 if( sqlite3ExprCompare(pParse
, pE1
, pE2
, iTab
)==0 ){
6169 && (sqlite3ExprImpliesExpr(pParse
, pE1
, pE2
->pLeft
, iTab
)
6170 || sqlite3ExprImpliesExpr(pParse
, pE1
, pE2
->pRight
, iTab
) )
6174 if( pE2
->op
==TK_NOTNULL
6175 && exprImpliesNotNull(pParse
, pE1
, pE2
->pLeft
, iTab
, 0)
6182 /* This is a helper function to impliesNotNullRow(). In this routine,
6183 ** set pWalker->eCode to one only if *both* of the input expressions
6184 ** separately have the implies-not-null-row property.
6186 static void bothImplyNotNullRow(Walker
*pWalker
, Expr
*pE1
, Expr
*pE2
){
6187 if( pWalker
->eCode
==0 ){
6188 sqlite3WalkExpr(pWalker
, pE1
);
6189 if( pWalker
->eCode
){
6191 sqlite3WalkExpr(pWalker
, pE2
);
6197 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
6198 ** If the expression node requires that the table at pWalker->iCur
6199 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
6201 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
6202 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when
6203 ** evaluating terms in the ON clause of an inner join.
6205 ** This routine controls an optimization. False positives (setting
6206 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
6207 ** (never setting pWalker->eCode) is a harmless missed optimization.
6209 static int impliesNotNullRow(Walker
*pWalker
, Expr
*pExpr
){
6210 testcase( pExpr
->op
==TK_AGG_COLUMN
);
6211 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
6212 if( ExprHasProperty(pExpr
, EP_OuterON
) ) return WRC_Prune
;
6213 if( ExprHasProperty(pExpr
, EP_InnerON
) && pWalker
->mWFlags
){
6214 /* If iCur is used in an inner-join ON clause to the left of a
6215 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
6216 ** But it is difficult to check for that condition precisely.
6217 ** To keep things simple, any use of iCur from any inner-join is
6218 ** ignored while attempting to simplify a RIGHT JOIN. */
6221 switch( pExpr
->op
){
6230 testcase( pExpr
->op
==TK_ISNOT
);
6231 testcase( pExpr
->op
==TK_ISNULL
);
6232 testcase( pExpr
->op
==TK_NOTNULL
);
6233 testcase( pExpr
->op
==TK_IS
);
6234 testcase( pExpr
->op
==TK_VECTOR
);
6235 testcase( pExpr
->op
==TK_FUNCTION
);
6236 testcase( pExpr
->op
==TK_TRUTH
);
6237 testcase( pExpr
->op
==TK_CASE
);
6241 if( pWalker
->u
.iCur
==pExpr
->iTable
){
6249 /* Both sides of an AND or OR must separately imply non-null-row.
6250 ** Consider these cases:
6253 ** If only one of x or y is non-null-row, then the overall expression
6254 ** can be true if the other arm is false (case 1) or true (case 2).
6256 testcase( pExpr
->op
==TK_OR
);
6257 testcase( pExpr
->op
==TK_AND
);
6258 bothImplyNotNullRow(pWalker
, pExpr
->pLeft
, pExpr
->pRight
);
6262 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
6263 ** both of which can be true. But apart from these cases, if
6264 ** the left-hand side of the IN is NULL then the IN itself will be
6266 if( ExprUseXList(pExpr
) && ALWAYS(pExpr
->x
.pList
->nExpr
>0) ){
6267 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
6272 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
6273 ** both y and z must be non-null row */
6274 assert( ExprUseXList(pExpr
) );
6275 assert( pExpr
->x
.pList
->nExpr
==2 );
6276 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
6277 bothImplyNotNullRow(pWalker
, pExpr
->x
.pList
->a
[0].pExpr
,
6278 pExpr
->x
.pList
->a
[1].pExpr
);
6281 /* Virtual tables are allowed to use constraints like x=NULL. So
6282 ** a term of the form x=y does not prove that y is not null if x
6283 ** is the column of a virtual table */
6290 Expr
*pLeft
= pExpr
->pLeft
;
6291 Expr
*pRight
= pExpr
->pRight
;
6292 testcase( pExpr
->op
==TK_EQ
);
6293 testcase( pExpr
->op
==TK_NE
);
6294 testcase( pExpr
->op
==TK_LT
);
6295 testcase( pExpr
->op
==TK_LE
);
6296 testcase( pExpr
->op
==TK_GT
);
6297 testcase( pExpr
->op
==TK_GE
);
6298 /* The y.pTab=0 assignment in wherecode.c always happens after the
6299 ** impliesNotNullRow() test */
6300 assert( pLeft
->op
!=TK_COLUMN
|| ExprUseYTab(pLeft
) );
6301 assert( pRight
->op
!=TK_COLUMN
|| ExprUseYTab(pRight
) );
6302 if( (pLeft
->op
==TK_COLUMN
6303 && ALWAYS(pLeft
->y
.pTab
!=0)
6304 && IsVirtual(pLeft
->y
.pTab
))
6305 || (pRight
->op
==TK_COLUMN
6306 && ALWAYS(pRight
->y
.pTab
!=0)
6307 && IsVirtual(pRight
->y
.pTab
))
6311 /* no break */ deliberate_fall_through
6314 return WRC_Continue
;
6319 ** Return true (non-zero) if expression p can only be true if at least
6320 ** one column of table iTab is non-null. In other words, return true
6321 ** if expression p will always be NULL or false if every column of iTab
6324 ** False negatives are acceptable. In other words, it is ok to return
6325 ** zero even if expression p will never be true of every column of iTab
6326 ** is NULL. A false negative is merely a missed optimization opportunity.
6328 ** False positives are not allowed, however. A false positive may result
6329 ** in an incorrect answer.
6331 ** Terms of p that are marked with EP_OuterON (and hence that come from
6332 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6334 ** This routine is used to check if a LEFT JOIN can be converted into
6335 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6336 ** clause requires that some column of the right table of the LEFT JOIN
6337 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6340 int sqlite3ExprImpliesNonNullRow(Expr
*p
, int iTab
, int isRJ
){
6342 p
= sqlite3ExprSkipCollateAndLikely(p
);
6343 if( p
==0 ) return 0;
6344 if( p
->op
==TK_NOTNULL
){
6347 while( p
->op
==TK_AND
){
6348 if( sqlite3ExprImpliesNonNullRow(p
->pLeft
, iTab
, isRJ
) ) return 1;
6352 w
.xExprCallback
= impliesNotNullRow
;
6353 w
.xSelectCallback
= 0;
6354 w
.xSelectCallback2
= 0;
6356 w
.mWFlags
= isRJ
!=0;
6358 sqlite3WalkExpr(&w
, p
);
6363 ** An instance of the following structure is used by the tree walker
6364 ** to determine if an expression can be evaluated by reference to the
6365 ** index only, without having to do a search for the corresponding
6366 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6367 ** is the cursor for the table.
6370 Index
*pIdx
; /* The index to be tested for coverage */
6371 int iCur
; /* Cursor number for the table corresponding to the index */
6375 ** Check to see if there are references to columns in table
6376 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6377 ** pWalker->u.pIdxCover->pIdx.
6379 static int exprIdxCover(Walker
*pWalker
, Expr
*pExpr
){
6380 if( pExpr
->op
==TK_COLUMN
6381 && pExpr
->iTable
==pWalker
->u
.pIdxCover
->iCur
6382 && sqlite3TableColumnToIndex(pWalker
->u
.pIdxCover
->pIdx
, pExpr
->iColumn
)<0
6387 return WRC_Continue
;
6391 ** Determine if an index pIdx on table with cursor iCur contains will
6392 ** the expression pExpr. Return true if the index does cover the
6393 ** expression and false if the pExpr expression references table columns
6394 ** that are not found in the index pIdx.
6396 ** An index covering an expression means that the expression can be
6397 ** evaluated using only the index and without having to lookup the
6398 ** corresponding table entry.
6400 int sqlite3ExprCoveredByIndex(
6401 Expr
*pExpr
, /* The index to be tested */
6402 int iCur
, /* The cursor number for the corresponding table */
6403 Index
*pIdx
/* The index that might be used for coverage */
6406 struct IdxCover xcov
;
6407 memset(&w
, 0, sizeof(w
));
6410 w
.xExprCallback
= exprIdxCover
;
6411 w
.u
.pIdxCover
= &xcov
;
6412 sqlite3WalkExpr(&w
, pExpr
);
6417 /* Structure used to pass information throughout the Walker in order to
6418 ** implement sqlite3ReferencesSrcList().
6421 sqlite3
*db
; /* Database connection used for sqlite3DbRealloc() */
6422 SrcList
*pRef
; /* Looking for references to these tables */
6423 i64 nExclude
; /* Number of tables to exclude from the search */
6424 int *aiExclude
; /* Cursor IDs for tables to exclude from the search */
6428 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6430 ** When entering a new subquery on the pExpr argument, add all FROM clause
6431 ** entries for that subquery to the exclude list.
6433 ** When leaving the subquery, remove those entries from the exclude list.
6435 static int selectRefEnter(Walker
*pWalker
, Select
*pSelect
){
6436 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6437 SrcList
*pSrc
= pSelect
->pSrc
;
6440 if( pSrc
->nSrc
==0 ) return WRC_Continue
;
6442 p
->nExclude
+= pSrc
->nSrc
;
6443 piNew
= sqlite3DbRealloc(p
->db
, p
->aiExclude
, p
->nExclude
*sizeof(int));
6448 p
->aiExclude
= piNew
;
6450 for(i
=0; i
<pSrc
->nSrc
; i
++, j
++){
6451 p
->aiExclude
[j
] = pSrc
->a
[i
].iCursor
;
6453 return WRC_Continue
;
6455 static void selectRefLeave(Walker
*pWalker
, Select
*pSelect
){
6456 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6457 SrcList
*pSrc
= pSelect
->pSrc
;
6459 assert( p
->nExclude
>=pSrc
->nSrc
);
6460 p
->nExclude
-= pSrc
->nSrc
;
6464 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6466 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6467 ** of the tables shown in RefSrcList.pRef.
6469 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6470 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6472 static int exprRefToSrcList(Walker
*pWalker
, Expr
*pExpr
){
6473 if( pExpr
->op
==TK_COLUMN
6474 || pExpr
->op
==TK_AGG_COLUMN
6477 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6478 SrcList
*pSrc
= p
->pRef
;
6479 int nSrc
= pSrc
? pSrc
->nSrc
: 0;
6480 for(i
=0; i
<nSrc
; i
++){
6481 if( pExpr
->iTable
==pSrc
->a
[i
].iCursor
){
6482 pWalker
->eCode
|= 1;
6483 return WRC_Continue
;
6486 for(i
=0; i
<p
->nExclude
&& p
->aiExclude
[i
]!=pExpr
->iTable
; i
++){}
6487 if( i
>=p
->nExclude
){
6488 pWalker
->eCode
|= 2;
6491 return WRC_Continue
;
6495 ** Check to see if pExpr references any tables in pSrcList.
6496 ** Possible return values:
6498 ** 1 pExpr does references a table in pSrcList.
6500 ** 0 pExpr references some table that is not defined in either
6501 ** pSrcList or in subqueries of pExpr itself.
6503 ** -1 pExpr only references no tables at all, or it only
6504 ** references tables defined in subqueries of pExpr itself.
6506 ** As currently used, pExpr is always an aggregate function call. That
6507 ** fact is exploited for efficiency.
6509 int sqlite3ReferencesSrcList(Parse
*pParse
, Expr
*pExpr
, SrcList
*pSrcList
){
6511 struct RefSrcList x
;
6512 assert( pParse
->db
!=0 );
6513 memset(&w
, 0, sizeof(w
));
6514 memset(&x
, 0, sizeof(x
));
6515 w
.xExprCallback
= exprRefToSrcList
;
6516 w
.xSelectCallback
= selectRefEnter
;
6517 w
.xSelectCallback2
= selectRefLeave
;
6518 w
.u
.pRefSrcList
= &x
;
6521 assert( pExpr
->op
==TK_AGG_FUNCTION
);
6522 assert( ExprUseXList(pExpr
) );
6523 sqlite3WalkExprList(&w
, pExpr
->x
.pList
);
6525 assert( pExpr
->pLeft
->op
==TK_ORDER
);
6526 assert( ExprUseXList(pExpr
->pLeft
) );
6527 assert( pExpr
->pLeft
->x
.pList
!=0 );
6528 sqlite3WalkExprList(&w
, pExpr
->pLeft
->x
.pList
);
6530 #ifndef SQLITE_OMIT_WINDOWFUNC
6531 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
6532 sqlite3WalkExpr(&w
, pExpr
->y
.pWin
->pFilter
);
6535 if( x
.aiExclude
) sqlite3DbNNFreeNN(pParse
->db
, x
.aiExclude
);
6536 if( w
.eCode
& 0x01 ){
6538 }else if( w
.eCode
){
6546 ** This is a Walker expression node callback.
6548 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6549 ** object that is referenced does not refer directly to the Expr. If
6550 ** it does, make a copy. This is done because the pExpr argument is
6551 ** subject to change.
6553 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6554 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6556 static int agginfoPersistExprCb(Walker
*pWalker
, Expr
*pExpr
){
6557 if( ALWAYS(!ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
))
6558 && pExpr
->pAggInfo
!=0
6560 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
6561 int iAgg
= pExpr
->iAgg
;
6562 Parse
*pParse
= pWalker
->pParse
;
6563 sqlite3
*db
= pParse
->db
;
6565 if( pExpr
->op
!=TK_AGG_FUNCTION
){
6566 if( iAgg
<pAggInfo
->nColumn
6567 && pAggInfo
->aCol
[iAgg
].pCExpr
==pExpr
6569 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
6571 pAggInfo
->aCol
[iAgg
].pCExpr
= pExpr
;
6572 sqlite3ExprDeferredDelete(pParse
, pExpr
);
6576 assert( pExpr
->op
==TK_AGG_FUNCTION
);
6577 if( ALWAYS(iAgg
<pAggInfo
->nFunc
)
6578 && pAggInfo
->aFunc
[iAgg
].pFExpr
==pExpr
6580 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
6582 pAggInfo
->aFunc
[iAgg
].pFExpr
= pExpr
;
6583 sqlite3ExprDeferredDelete(pParse
, pExpr
);
6588 return WRC_Continue
;
6592 ** Initialize a Walker object so that will persist AggInfo entries referenced
6593 ** by the tree that is walked.
6595 void sqlite3AggInfoPersistWalkerInit(Walker
*pWalker
, Parse
*pParse
){
6596 memset(pWalker
, 0, sizeof(*pWalker
));
6597 pWalker
->pParse
= pParse
;
6598 pWalker
->xExprCallback
= agginfoPersistExprCb
;
6599 pWalker
->xSelectCallback
= sqlite3SelectWalkNoop
;
6603 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6604 ** the new element. Return a negative number if malloc fails.
6606 static int addAggInfoColumn(sqlite3
*db
, AggInfo
*pInfo
){
6608 pInfo
->aCol
= sqlite3ArrayAllocate(
6611 sizeof(pInfo
->aCol
[0]),
6619 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6620 ** the new element. Return a negative number if malloc fails.
6622 static int addAggInfoFunc(sqlite3
*db
, AggInfo
*pInfo
){
6624 pInfo
->aFunc
= sqlite3ArrayAllocate(
6627 sizeof(pInfo
->aFunc
[0]),
6635 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6636 ** Return the index in aCol[] of the entry that describes that column.
6638 ** If no prior entry is found, create a new one and return -1. The
6639 ** new column will have an index of pAggInfo->nColumn-1.
6641 static void findOrCreateAggInfoColumn(
6642 Parse
*pParse
, /* Parsing context */
6643 AggInfo
*pAggInfo
, /* The AggInfo object to search and/or modify */
6644 Expr
*pExpr
/* Expr describing the column to find or insert */
6646 struct AggInfo_col
*pCol
;
6649 assert( pAggInfo
->iFirstReg
==0 );
6650 pCol
= pAggInfo
->aCol
;
6651 for(k
=0; k
<pAggInfo
->nColumn
; k
++, pCol
++){
6652 if( pCol
->pCExpr
==pExpr
) return;
6653 if( pCol
->iTable
==pExpr
->iTable
6654 && pCol
->iColumn
==pExpr
->iColumn
6655 && pExpr
->op
!=TK_IF_NULL_ROW
6660 k
= addAggInfoColumn(pParse
->db
, pAggInfo
);
6663 assert( pParse
->db
->mallocFailed
);
6666 pCol
= &pAggInfo
->aCol
[k
];
6667 assert( ExprUseYTab(pExpr
) );
6668 pCol
->pTab
= pExpr
->y
.pTab
;
6669 pCol
->iTable
= pExpr
->iTable
;
6670 pCol
->iColumn
= pExpr
->iColumn
;
6671 pCol
->iSorterColumn
= -1;
6672 pCol
->pCExpr
= pExpr
;
6673 if( pAggInfo
->pGroupBy
&& pExpr
->op
!=TK_IF_NULL_ROW
){
6675 ExprList
*pGB
= pAggInfo
->pGroupBy
;
6676 struct ExprList_item
*pTerm
= pGB
->a
;
6678 for(j
=0; j
<n
; j
++, pTerm
++){
6679 Expr
*pE
= pTerm
->pExpr
;
6680 if( pE
->op
==TK_COLUMN
6681 && pE
->iTable
==pExpr
->iTable
6682 && pE
->iColumn
==pExpr
->iColumn
6684 pCol
->iSorterColumn
= j
;
6689 if( pCol
->iSorterColumn
<0 ){
6690 pCol
->iSorterColumn
= pAggInfo
->nSortingColumn
++;
6693 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
6694 assert( pExpr
->pAggInfo
==0 || pExpr
->pAggInfo
==pAggInfo
);
6695 pExpr
->pAggInfo
= pAggInfo
;
6696 if( pExpr
->op
==TK_COLUMN
){
6697 pExpr
->op
= TK_AGG_COLUMN
;
6699 pExpr
->iAgg
= (i16
)k
;
6703 ** This is the xExprCallback for a tree walker. It is used to
6704 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
6705 ** for additional information.
6707 static int analyzeAggregate(Walker
*pWalker
, Expr
*pExpr
){
6709 NameContext
*pNC
= pWalker
->u
.pNC
;
6710 Parse
*pParse
= pNC
->pParse
;
6711 SrcList
*pSrcList
= pNC
->pSrcList
;
6712 AggInfo
*pAggInfo
= pNC
->uNC
.pAggInfo
;
6714 assert( pNC
->ncFlags
& NC_UAggInfo
);
6715 assert( pAggInfo
->iFirstReg
==0 );
6716 switch( pExpr
->op
){
6720 assert( pParse
->iSelfTab
==0 );
6721 if( (pNC
->ncFlags
& NC_InAggFunc
)==0 ) break;
6722 if( pParse
->pIdxEpr
==0 ) break;
6723 for(pIEpr
=pParse
->pIdxEpr
; pIEpr
; pIEpr
=pIEpr
->pIENext
){
6724 int iDataCur
= pIEpr
->iDataCur
;
6725 if( iDataCur
<0 ) continue;
6726 if( sqlite3ExprCompare(0, pExpr
, pIEpr
->pExpr
, iDataCur
)==0 ) break;
6728 if( pIEpr
==0 ) break;
6729 if( NEVER(!ExprUseYTab(pExpr
)) ) break;
6730 for(i
=0; i
<pSrcList
->nSrc
; i
++){
6731 if( pSrcList
->a
[0].iCursor
==pIEpr
->iDataCur
) break;
6733 if( i
>=pSrcList
->nSrc
) break;
6734 if( NEVER(pExpr
->pAggInfo
!=0) ) break; /* Resolved by outer context */
6735 if( pParse
->nErr
){ return WRC_Abort
; }
6737 /* If we reach this point, it means that expression pExpr can be
6738 ** translated into a reference to an index column as described by
6741 memset(&tmp
, 0, sizeof(tmp
));
6742 tmp
.op
= TK_AGG_COLUMN
;
6743 tmp
.iTable
= pIEpr
->iIdxCur
;
6744 tmp
.iColumn
= pIEpr
->iIdxCol
;
6745 findOrCreateAggInfoColumn(pParse
, pAggInfo
, &tmp
);
6746 if( pParse
->nErr
){ return WRC_Abort
; }
6747 assert( pAggInfo
->aCol
!=0 );
6748 assert( tmp
.iAgg
<pAggInfo
->nColumn
);
6749 pAggInfo
->aCol
[tmp
.iAgg
].pCExpr
= pExpr
;
6750 pExpr
->pAggInfo
= pAggInfo
;
6751 pExpr
->iAgg
= tmp
.iAgg
;
6754 case TK_IF_NULL_ROW
:
6757 testcase( pExpr
->op
==TK_AGG_COLUMN
);
6758 testcase( pExpr
->op
==TK_COLUMN
);
6759 testcase( pExpr
->op
==TK_IF_NULL_ROW
);
6760 /* Check to see if the column is in one of the tables in the FROM
6761 ** clause of the aggregate query */
6762 if( ALWAYS(pSrcList
!=0) ){
6763 SrcItem
*pItem
= pSrcList
->a
;
6764 for(i
=0; i
<pSrcList
->nSrc
; i
++, pItem
++){
6765 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
6766 if( pExpr
->iTable
==pItem
->iCursor
){
6767 findOrCreateAggInfoColumn(pParse
, pAggInfo
, pExpr
);
6769 } /* endif pExpr->iTable==pItem->iCursor */
6770 } /* end loop over pSrcList */
6772 return WRC_Continue
;
6774 case TK_AGG_FUNCTION
: {
6775 if( (pNC
->ncFlags
& NC_InAggFunc
)==0
6776 && pWalker
->walkerDepth
==pExpr
->op2
6777 && pExpr
->pAggInfo
==0
6779 /* Check to see if pExpr is a duplicate of another aggregate
6780 ** function that is already in the pAggInfo structure
6782 struct AggInfo_func
*pItem
= pAggInfo
->aFunc
;
6783 for(i
=0; i
<pAggInfo
->nFunc
; i
++, pItem
++){
6784 if( NEVER(pItem
->pFExpr
==pExpr
) ) break;
6785 if( sqlite3ExprCompare(0, pItem
->pFExpr
, pExpr
, -1)==0 ){
6789 if( i
>=pAggInfo
->nFunc
){
6790 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
6792 u8 enc
= ENC(pParse
->db
);
6793 i
= addAggInfoFunc(pParse
->db
, pAggInfo
);
6796 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
6797 pItem
= &pAggInfo
->aFunc
[i
];
6798 pItem
->pFExpr
= pExpr
;
6799 assert( ExprUseUToken(pExpr
) );
6800 nArg
= pExpr
->x
.pList
? pExpr
->x
.pList
->nExpr
: 0;
6801 pItem
->pFunc
= sqlite3FindFunction(pParse
->db
,
6802 pExpr
->u
.zToken
, nArg
, enc
, 0);
6803 assert( pItem
->bOBUnique
==0 );
6805 && (pItem
->pFunc
->funcFlags
& SQLITE_FUNC_NEEDCOLL
)==0
6807 /* The NEEDCOLL test above causes any ORDER BY clause on
6808 ** aggregate min() or max() to be ignored. */
6811 assert( pExpr
->pLeft
->op
==TK_ORDER
);
6812 assert( ExprUseXList(pExpr
->pLeft
) );
6813 pItem
->iOBTab
= pParse
->nTab
++;
6814 pOBList
= pExpr
->pLeft
->x
.pList
;
6815 assert( pOBList
->nExpr
>0 );
6816 assert( pItem
->bOBUnique
==0 );
6817 if( pOBList
->nExpr
==1
6819 && sqlite3ExprCompare(0,pOBList
->a
[0].pExpr
,
6820 pExpr
->x
.pList
->a
[0].pExpr
,0)==0
6822 pItem
->bOBPayload
= 0;
6823 pItem
->bOBUnique
= ExprHasProperty(pExpr
, EP_Distinct
);
6825 pItem
->bOBPayload
= 1;
6827 pItem
->bUseSubtype
=
6828 (pItem
->pFunc
->funcFlags
& SQLITE_SUBTYPE
)!=0;
6832 if( ExprHasProperty(pExpr
, EP_Distinct
) && !pItem
->bOBUnique
){
6833 pItem
->iDistinct
= pParse
->nTab
++;
6835 pItem
->iDistinct
= -1;
6839 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6841 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
6842 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
6843 pExpr
->iAgg
= (i16
)i
;
6844 pExpr
->pAggInfo
= pAggInfo
;
6847 return WRC_Continue
;
6851 return WRC_Continue
;
6855 ** Analyze the pExpr expression looking for aggregate functions and
6856 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6857 ** points to. Additional entries are made on the AggInfo object as
6860 ** This routine should only be called after the expression has been
6861 ** analyzed by sqlite3ResolveExprNames().
6863 void sqlite3ExprAnalyzeAggregates(NameContext
*pNC
, Expr
*pExpr
){
6865 w
.xExprCallback
= analyzeAggregate
;
6866 w
.xSelectCallback
= sqlite3WalkerDepthIncrease
;
6867 w
.xSelectCallback2
= sqlite3WalkerDepthDecrease
;
6871 assert( pNC
->pSrcList
!=0 );
6872 sqlite3WalkExpr(&w
, pExpr
);
6876 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
6877 ** expression list. Return the number of errors.
6879 ** If an error is found, the analysis is cut short.
6881 void sqlite3ExprAnalyzeAggList(NameContext
*pNC
, ExprList
*pList
){
6882 struct ExprList_item
*pItem
;
6885 for(pItem
=pList
->a
, i
=0; i
<pList
->nExpr
; i
++, pItem
++){
6886 sqlite3ExprAnalyzeAggregates(pNC
, pItem
->pExpr
);
6892 ** Allocate a single new register for use to hold some intermediate result.
6894 int sqlite3GetTempReg(Parse
*pParse
){
6895 if( pParse
->nTempReg
==0 ){
6896 return ++pParse
->nMem
;
6898 return pParse
->aTempReg
[--pParse
->nTempReg
];
6902 ** Deallocate a register, making available for reuse for some other
6905 void sqlite3ReleaseTempReg(Parse
*pParse
, int iReg
){
6907 sqlite3VdbeReleaseRegisters(pParse
, iReg
, 1, 0, 0);
6908 if( pParse
->nTempReg
<ArraySize(pParse
->aTempReg
) ){
6909 pParse
->aTempReg
[pParse
->nTempReg
++] = iReg
;
6915 ** Allocate or deallocate a block of nReg consecutive registers.
6917 int sqlite3GetTempRange(Parse
*pParse
, int nReg
){
6919 if( nReg
==1 ) return sqlite3GetTempReg(pParse
);
6920 i
= pParse
->iRangeReg
;
6921 n
= pParse
->nRangeReg
;
6923 pParse
->iRangeReg
+= nReg
;
6924 pParse
->nRangeReg
-= nReg
;
6927 pParse
->nMem
+= nReg
;
6931 void sqlite3ReleaseTempRange(Parse
*pParse
, int iReg
, int nReg
){
6933 sqlite3ReleaseTempReg(pParse
, iReg
);
6936 sqlite3VdbeReleaseRegisters(pParse
, iReg
, nReg
, 0, 0);
6937 if( nReg
>pParse
->nRangeReg
){
6938 pParse
->nRangeReg
= nReg
;
6939 pParse
->iRangeReg
= iReg
;
6944 ** Mark all temporary registers as being unavailable for reuse.
6946 ** Always invoke this procedure after coding a subroutine or co-routine
6947 ** that might be invoked from other parts of the code, to ensure that
6948 ** the sub/co-routine does not use registers in common with the code that
6949 ** invokes the sub/co-routine.
6951 void sqlite3ClearTempRegCache(Parse
*pParse
){
6952 pParse
->nTempReg
= 0;
6953 pParse
->nRangeReg
= 0;
6957 ** Make sure sufficient registers have been allocated so that
6958 ** iReg is a valid register number.
6960 void sqlite3TouchRegister(Parse
*pParse
, int iReg
){
6961 if( pParse
->nMem
<iReg
) pParse
->nMem
= iReg
;
6964 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
6966 ** Return the latest reusable register in the set of all registers.
6967 ** The value returned is no less than iMin. If any register iMin or
6968 ** greater is in permanent use, then return one more than that last
6969 ** permanent register.
6971 int sqlite3FirstAvailableRegister(Parse
*pParse
, int iMin
){
6972 const ExprList
*pList
= pParse
->pConstExpr
;
6975 for(i
=0; i
<pList
->nExpr
; i
++){
6976 if( pList
->a
[i
].u
.iConstExprReg
>=iMin
){
6977 iMin
= pList
->a
[i
].u
.iConstExprReg
+ 1;
6981 pParse
->nTempReg
= 0;
6982 pParse
->nRangeReg
= 0;
6985 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
6988 ** Validate that no temporary register falls within the range of
6989 ** iFirst..iLast, inclusive. This routine is only call from within assert()
6993 int sqlite3NoTempsInRange(Parse
*pParse
, int iFirst
, int iLast
){
6995 if( pParse
->nRangeReg
>0
6996 && pParse
->iRangeReg
+pParse
->nRangeReg
> iFirst
6997 && pParse
->iRangeReg
<= iLast
7001 for(i
=0; i
<pParse
->nTempReg
; i
++){
7002 if( pParse
->aTempReg
[i
]>=iFirst
&& pParse
->aTempReg
[i
]<=iLast
){
7006 if( pParse
->pConstExpr
){
7007 ExprList
*pList
= pParse
->pConstExpr
;
7008 for(i
=0; i
<pList
->nExpr
; i
++){
7009 int iReg
= pList
->a
[i
].u
.iConstExprReg
;
7010 if( iReg
==0 ) continue;
7011 if( iReg
>=iFirst
&& iReg
<=iLast
) return 0;
7016 #endif /* SQLITE_DEBUG */