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"
18 ** Return the 'affinity' of the expression pExpr if any.
20 ** If pExpr is a column, a reference to a column via an 'AS' alias,
21 ** or a sub-select with a column as the return value, then the
22 ** affinity of that column is returned. Otherwise, 0x00 is returned,
23 ** indicating no affinity for the expression.
25 ** i.e. the WHERE clause expressions in the following statements all
28 ** CREATE TABLE t1(a);
29 ** SELECT * FROM t1 WHERE a;
30 ** SELECT a AS b FROM t1 WHERE b;
31 ** SELECT * FROM t1 WHERE (select a from t1);
33 char sqlite3ExprAffinity(Expr
*pExpr
){
35 pExpr
= sqlite3ExprSkipCollate(pExpr
);
36 if( pExpr
->flags
& EP_Generic
) return 0;
39 assert( pExpr
->flags
&EP_xIsSelect
);
40 return sqlite3ExprAffinity(pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
);
42 #ifndef SQLITE_OMIT_CAST
44 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
45 return sqlite3AffinityType(pExpr
->u
.zToken
, 0);
48 if( (op
==TK_AGG_COLUMN
|| op
==TK_COLUMN
|| op
==TK_REGISTER
)
51 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
52 ** a TK_COLUMN but was previously evaluated and cached in a register */
53 int j
= pExpr
->iColumn
;
54 if( j
<0 ) return SQLITE_AFF_INTEGER
;
55 assert( pExpr
->pTab
&& j
<pExpr
->pTab
->nCol
);
56 return pExpr
->pTab
->aCol
[j
].affinity
;
58 return pExpr
->affinity
;
62 ** Set the collating sequence for expression pExpr to be the collating
63 ** sequence named by pToken. Return a pointer to a new Expr node that
64 ** implements the COLLATE operator.
66 ** If a memory allocation error occurs, that fact is recorded in pParse->db
67 ** and the pExpr parameter is returned unchanged.
69 Expr
*sqlite3ExprAddCollateToken(
70 Parse
*pParse
, /* Parsing context */
71 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
72 const Token
*pCollName
/* Name of collating sequence */
75 Expr
*pNew
= sqlite3ExprAlloc(pParse
->db
, TK_COLLATE
, pCollName
, 1);
78 pNew
->flags
|= EP_Collate
|EP_Skip
;
84 Expr
*sqlite3ExprAddCollateString(Parse
*pParse
, Expr
*pExpr
, const char *zC
){
88 s
.n
= sqlite3Strlen30(s
.z
);
89 return sqlite3ExprAddCollateToken(pParse
, pExpr
, &s
);
93 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
94 ** or likelihood() function at the root of an expression.
96 Expr
*sqlite3ExprSkipCollate(Expr
*pExpr
){
97 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
) ){
98 if( ExprHasProperty(pExpr
, EP_Unlikely
) ){
99 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
100 assert( pExpr
->x
.pList
->nExpr
>0 );
101 assert( pExpr
->op
==TK_FUNCTION
);
102 pExpr
= pExpr
->x
.pList
->a
[0].pExpr
;
104 assert( pExpr
->op
==TK_COLLATE
|| pExpr
->op
==TK_AS
);
105 pExpr
= pExpr
->pLeft
;
112 ** Return the collation sequence for the expression pExpr. If
113 ** there is no defined collating sequence, return NULL.
115 ** The collating sequence might be determined by a COLLATE operator
116 ** or by the presence of a column with a defined collating sequence.
117 ** COLLATE operators take first precedence. Left operands take
118 ** precedence over right operands.
120 CollSeq
*sqlite3ExprCollSeq(Parse
*pParse
, Expr
*pExpr
){
121 sqlite3
*db
= pParse
->db
;
126 if( p
->flags
& EP_Generic
) break;
127 if( op
==TK_CAST
|| op
==TK_UPLUS
){
131 if( op
==TK_COLLATE
|| (op
==TK_REGISTER
&& p
->op2
==TK_COLLATE
) ){
132 pColl
= sqlite3GetCollSeq(pParse
, ENC(db
), 0, p
->u
.zToken
);
136 && (op
==TK_AGG_COLUMN
|| op
==TK_COLUMN
137 || op
==TK_REGISTER
|| op
==TK_TRIGGER
)
139 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
140 ** a TK_COLUMN but was previously evaluated and cached in a register */
143 const char *zColl
= p
->pTab
->aCol
[j
].zColl
;
144 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
148 if( p
->flags
& EP_Collate
){
149 if( ALWAYS(p
->pLeft
) && (p
->pLeft
->flags
& EP_Collate
)!=0 ){
158 if( sqlite3CheckCollSeq(pParse
, pColl
) ){
165 ** pExpr is an operand of a comparison operator. aff2 is the
166 ** type affinity of the other operand. This routine returns the
167 ** type affinity that should be used for the comparison operator.
169 char sqlite3CompareAffinity(Expr
*pExpr
, char aff2
){
170 char aff1
= sqlite3ExprAffinity(pExpr
);
172 /* Both sides of the comparison are columns. If one has numeric
173 ** affinity, use that. Otherwise use no affinity.
175 if( sqlite3IsNumericAffinity(aff1
) || sqlite3IsNumericAffinity(aff2
) ){
176 return SQLITE_AFF_NUMERIC
;
178 return SQLITE_AFF_NONE
;
180 }else if( !aff1
&& !aff2
){
181 /* Neither side of the comparison is a column. Compare the
184 return SQLITE_AFF_NONE
;
186 /* One side is a column, the other is not. Use the columns affinity. */
187 assert( aff1
==0 || aff2
==0 );
188 return (aff1
+ aff2
);
193 ** pExpr is a comparison operator. Return the type affinity that should
194 ** be applied to both operands prior to doing the comparison.
196 static char comparisonAffinity(Expr
*pExpr
){
198 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_IN
|| pExpr
->op
==TK_LT
||
199 pExpr
->op
==TK_GT
|| pExpr
->op
==TK_GE
|| pExpr
->op
==TK_LE
||
200 pExpr
->op
==TK_NE
|| pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
);
201 assert( pExpr
->pLeft
);
202 aff
= sqlite3ExprAffinity(pExpr
->pLeft
);
204 aff
= sqlite3CompareAffinity(pExpr
->pRight
, aff
);
205 }else if( ExprHasProperty(pExpr
, EP_xIsSelect
) ){
206 aff
= sqlite3CompareAffinity(pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
, aff
);
208 aff
= SQLITE_AFF_NONE
;
214 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
215 ** idx_affinity is the affinity of an indexed column. Return true
216 ** if the index with affinity idx_affinity may be used to implement
217 ** the comparison in pExpr.
219 int sqlite3IndexAffinityOk(Expr
*pExpr
, char idx_affinity
){
220 char aff
= comparisonAffinity(pExpr
);
222 case SQLITE_AFF_NONE
:
224 case SQLITE_AFF_TEXT
:
225 return idx_affinity
==SQLITE_AFF_TEXT
;
227 return sqlite3IsNumericAffinity(idx_affinity
);
232 ** Return the P5 value that should be used for a binary comparison
233 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
235 static u8
binaryCompareP5(Expr
*pExpr1
, Expr
*pExpr2
, int jumpIfNull
){
236 u8 aff
= (char)sqlite3ExprAffinity(pExpr2
);
237 aff
= (u8
)sqlite3CompareAffinity(pExpr1
, aff
) | (u8
)jumpIfNull
;
242 ** Return a pointer to the collation sequence that should be used by
243 ** a binary comparison operator comparing pLeft and pRight.
245 ** If the left hand expression has a collating sequence type, then it is
246 ** used. Otherwise the collation sequence for the right hand expression
247 ** is used, or the default (BINARY) if neither expression has a collating
250 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
251 ** it is not considered.
253 CollSeq
*sqlite3BinaryCompareCollSeq(
260 if( pLeft
->flags
& EP_Collate
){
261 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
262 }else if( pRight
&& (pRight
->flags
& EP_Collate
)!=0 ){
263 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
265 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
267 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
274 ** Generate code for a comparison operator.
276 static int codeCompare(
277 Parse
*pParse
, /* The parsing (and code generating) context */
278 Expr
*pLeft
, /* The left operand */
279 Expr
*pRight
, /* The right operand */
280 int opcode
, /* The comparison opcode */
281 int in1
, int in2
, /* Register holding operands */
282 int dest
, /* Jump here if true. */
283 int jumpIfNull
/* If true, jump if either operand is NULL */
289 p4
= sqlite3BinaryCompareCollSeq(pParse
, pLeft
, pRight
);
290 p5
= binaryCompareP5(pLeft
, pRight
, jumpIfNull
);
291 addr
= sqlite3VdbeAddOp4(pParse
->pVdbe
, opcode
, in2
, dest
, in1
,
292 (void*)p4
, P4_COLLSEQ
);
293 sqlite3VdbeChangeP5(pParse
->pVdbe
, (u8
)p5
);
297 #if SQLITE_MAX_EXPR_DEPTH>0
299 ** Check that argument nHeight is less than or equal to the maximum
300 ** expression depth allowed. If it is not, leave an error message in
303 int sqlite3ExprCheckHeight(Parse
*pParse
, int nHeight
){
305 int mxHeight
= pParse
->db
->aLimit
[SQLITE_LIMIT_EXPR_DEPTH
];
306 if( nHeight
>mxHeight
){
307 sqlite3ErrorMsg(pParse
,
308 "Expression tree is too large (maximum depth %d)", mxHeight
315 /* The following three functions, heightOfExpr(), heightOfExprList()
316 ** and heightOfSelect(), are used to determine the maximum height
317 ** of any expression tree referenced by the structure passed as the
320 ** If this maximum height is greater than the current value pointed
321 ** to by pnHeight, the second parameter, then set *pnHeight to that
324 static void heightOfExpr(Expr
*p
, int *pnHeight
){
326 if( p
->nHeight
>*pnHeight
){
327 *pnHeight
= p
->nHeight
;
331 static void heightOfExprList(ExprList
*p
, int *pnHeight
){
334 for(i
=0; i
<p
->nExpr
; i
++){
335 heightOfExpr(p
->a
[i
].pExpr
, pnHeight
);
339 static void heightOfSelect(Select
*p
, int *pnHeight
){
341 heightOfExpr(p
->pWhere
, pnHeight
);
342 heightOfExpr(p
->pHaving
, pnHeight
);
343 heightOfExpr(p
->pLimit
, pnHeight
);
344 heightOfExpr(p
->pOffset
, pnHeight
);
345 heightOfExprList(p
->pEList
, pnHeight
);
346 heightOfExprList(p
->pGroupBy
, pnHeight
);
347 heightOfExprList(p
->pOrderBy
, pnHeight
);
348 heightOfSelect(p
->pPrior
, pnHeight
);
353 ** Set the Expr.nHeight variable in the structure passed as an
354 ** argument. An expression with no children, Expr.pList or
355 ** Expr.pSelect member has a height of 1. Any other expression
356 ** has a height equal to the maximum height of any other
357 ** referenced Expr plus one.
359 static void exprSetHeight(Expr
*p
){
361 heightOfExpr(p
->pLeft
, &nHeight
);
362 heightOfExpr(p
->pRight
, &nHeight
);
363 if( ExprHasProperty(p
, EP_xIsSelect
) ){
364 heightOfSelect(p
->x
.pSelect
, &nHeight
);
366 heightOfExprList(p
->x
.pList
, &nHeight
);
368 p
->nHeight
= nHeight
+ 1;
372 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
373 ** the height is greater than the maximum allowed expression depth,
374 ** leave an error in pParse.
376 void sqlite3ExprSetHeight(Parse
*pParse
, Expr
*p
){
378 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
382 ** Return the maximum height of any expression tree referenced
383 ** by the select statement passed as an argument.
385 int sqlite3SelectExprHeight(Select
*p
){
387 heightOfSelect(p
, &nHeight
);
391 #define exprSetHeight(y)
392 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
395 ** This routine is the core allocator for Expr nodes.
397 ** Construct a new expression node and return a pointer to it. Memory
398 ** for this node and for the pToken argument is a single allocation
399 ** obtained from sqlite3DbMalloc(). The calling function
400 ** is responsible for making sure the node eventually gets freed.
402 ** If dequote is true, then the token (if it exists) is dequoted.
403 ** If dequote is false, no dequoting is performance. The deQuote
404 ** parameter is ignored if pToken is NULL or if the token does not
405 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
406 ** then the EP_DblQuoted flag is set on the expression node.
408 ** Special case: If op==TK_INTEGER and pToken points to a string that
409 ** can be translated into a 32-bit integer, then the token is not
410 ** stored in u.zToken. Instead, the integer values is written
411 ** into u.iValue and the EP_IntValue flag is set. No extra storage
412 ** is allocated to hold the integer text and the dequote flag is ignored.
414 Expr
*sqlite3ExprAlloc(
415 sqlite3
*db
, /* Handle for sqlite3DbMallocZero() (may be null) */
416 int op
, /* Expression opcode */
417 const Token
*pToken
, /* Token argument. Might be NULL */
418 int dequote
/* True to dequote */
425 if( op
!=TK_INTEGER
|| pToken
->z
==0
426 || sqlite3GetInt32(pToken
->z
, &iValue
)==0 ){
427 nExtra
= pToken
->n
+1;
431 pNew
= sqlite3DbMallocZero(db
, sizeof(Expr
)+nExtra
);
437 pNew
->flags
|= EP_IntValue
;
438 pNew
->u
.iValue
= iValue
;
441 pNew
->u
.zToken
= (char*)&pNew
[1];
442 assert( pToken
->z
!=0 || pToken
->n
==0 );
443 if( pToken
->n
) memcpy(pNew
->u
.zToken
, pToken
->z
, pToken
->n
);
444 pNew
->u
.zToken
[pToken
->n
] = 0;
445 if( dequote
&& nExtra
>=3
446 && ((c
= pToken
->z
[0])=='\'' || c
=='"' || c
=='[' || c
=='`') ){
447 sqlite3Dequote(pNew
->u
.zToken
);
448 if( c
=='"' ) pNew
->flags
|= EP_DblQuoted
;
452 #if SQLITE_MAX_EXPR_DEPTH>0
460 ** Allocate a new expression node from a zero-terminated token that has
461 ** already been dequoted.
464 sqlite3
*db
, /* Handle for sqlite3DbMallocZero() (may be null) */
465 int op
, /* Expression opcode */
466 const char *zToken
/* Token argument. Might be NULL */
470 x
.n
= zToken
? sqlite3Strlen30(zToken
) : 0;
471 return sqlite3ExprAlloc(db
, op
, &x
, 0);
475 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
477 ** If pRoot==NULL that means that a memory allocation error has occurred.
478 ** In that case, delete the subtrees pLeft and pRight.
480 void sqlite3ExprAttachSubtrees(
487 assert( db
->mallocFailed
);
488 sqlite3ExprDelete(db
, pLeft
);
489 sqlite3ExprDelete(db
, pRight
);
492 pRoot
->pRight
= pRight
;
493 pRoot
->flags
|= EP_Collate
& pRight
->flags
;
496 pRoot
->pLeft
= pLeft
;
497 pRoot
->flags
|= EP_Collate
& pLeft
->flags
;
499 exprSetHeight(pRoot
);
504 ** Allocate an Expr node which joins as many as two subtrees.
506 ** One or both of the subtrees can be NULL. Return a pointer to the new
507 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
508 ** free the subtrees and return NULL.
511 Parse
*pParse
, /* Parsing context */
512 int op
, /* Expression opcode */
513 Expr
*pLeft
, /* Left operand */
514 Expr
*pRight
, /* Right operand */
515 const Token
*pToken
/* Argument token */
518 if( op
==TK_AND
&& pLeft
&& pRight
){
519 /* Take advantage of short-circuit false optimization for AND */
520 p
= sqlite3ExprAnd(pParse
->db
, pLeft
, pRight
);
522 p
= sqlite3ExprAlloc(pParse
->db
, op
, pToken
, 1);
523 sqlite3ExprAttachSubtrees(pParse
->db
, p
, pLeft
, pRight
);
526 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
532 ** If the expression is always either TRUE or FALSE (respectively),
533 ** then return 1. If one cannot determine the truth value of the
534 ** expression at compile-time return 0.
536 ** This is an optimization. If is OK to return 0 here even if
537 ** the expression really is always false or false (a false negative).
538 ** But it is a bug to return 1 if the expression might have different
539 ** boolean values in different circumstances (a false positive.)
541 ** Note that if the expression is part of conditional for a
542 ** LEFT JOIN, then we cannot determine at compile-time whether or not
543 ** is it true or false, so always return 0.
545 static int exprAlwaysTrue(Expr
*p
){
547 if( ExprHasProperty(p
, EP_FromJoin
) ) return 0;
548 if( !sqlite3ExprIsInteger(p
, &v
) ) return 0;
551 static int exprAlwaysFalse(Expr
*p
){
553 if( ExprHasProperty(p
, EP_FromJoin
) ) return 0;
554 if( !sqlite3ExprIsInteger(p
, &v
) ) return 0;
559 ** Join two expressions using an AND operator. If either expression is
560 ** NULL, then just return the other expression.
562 ** If one side or the other of the AND is known to be false, then instead
563 ** of returning an AND expression, just return a constant expression with
566 Expr
*sqlite3ExprAnd(sqlite3
*db
, Expr
*pLeft
, Expr
*pRight
){
569 }else if( pRight
==0 ){
571 }else if( exprAlwaysFalse(pLeft
) || exprAlwaysFalse(pRight
) ){
572 sqlite3ExprDelete(db
, pLeft
);
573 sqlite3ExprDelete(db
, pRight
);
574 return sqlite3ExprAlloc(db
, TK_INTEGER
, &sqlite3IntTokens
[0], 0);
576 Expr
*pNew
= sqlite3ExprAlloc(db
, TK_AND
, 0, 0);
577 sqlite3ExprAttachSubtrees(db
, pNew
, pLeft
, pRight
);
583 ** Construct a new expression node for a function with multiple
586 Expr
*sqlite3ExprFunction(Parse
*pParse
, ExprList
*pList
, Token
*pToken
){
588 sqlite3
*db
= pParse
->db
;
590 pNew
= sqlite3ExprAlloc(db
, TK_FUNCTION
, pToken
, 1);
592 sqlite3ExprListDelete(db
, pList
); /* Avoid memory leak when malloc fails */
595 pNew
->x
.pList
= pList
;
596 assert( !ExprHasProperty(pNew
, EP_xIsSelect
) );
597 sqlite3ExprSetHeight(pParse
, pNew
);
602 ** Assign a variable number to an expression that encodes a wildcard
603 ** in the original SQL statement.
605 ** Wildcards consisting of a single "?" are assigned the next sequential
608 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
609 ** sure "nnn" is not too be to avoid a denial of service attack when
610 ** the SQL statement comes from an external source.
612 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
613 ** as the previous instance of the same wildcard. Or if this is the first
614 ** instance of the wildcard, the next sequential variable number is
617 void sqlite3ExprAssignVarNumber(Parse
*pParse
, Expr
*pExpr
){
618 sqlite3
*db
= pParse
->db
;
621 if( pExpr
==0 ) return;
622 assert( !ExprHasProperty(pExpr
, EP_IntValue
|EP_Reduced
|EP_TokenOnly
) );
627 /* Wildcard of the form "?". Assign the next variable number */
629 pExpr
->iColumn
= (ynVar
)(++pParse
->nVar
);
632 u32 n
= sqlite3Strlen30(z
);
634 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
635 ** use it as the variable number */
637 int bOk
= 0==sqlite3Atoi64(&z
[1], &i
, n
-1, SQLITE_UTF8
);
638 pExpr
->iColumn
= x
= (ynVar
)i
;
641 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]-1 );
642 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] );
643 if( bOk
==0 || i
<1 || i
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
644 sqlite3ErrorMsg(pParse
, "variable number must be between ?1 and ?%d",
645 db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]);
648 if( i
>pParse
->nVar
){
649 pParse
->nVar
= (int)i
;
652 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
653 ** number as the prior appearance of the same name, or if the name
654 ** has never appeared before, reuse the same variable number
657 for(i
=0; i
<pParse
->nzVar
; i
++){
658 if( pParse
->azVar
[i
] && strcmp(pParse
->azVar
[i
],z
)==0 ){
659 pExpr
->iColumn
= x
= (ynVar
)i
+1;
663 if( x
==0 ) x
= pExpr
->iColumn
= (ynVar
)(++pParse
->nVar
);
666 if( x
>pParse
->nzVar
){
668 a
= sqlite3DbRealloc(db
, pParse
->azVar
, x
*sizeof(a
[0]));
669 if( a
==0 ) return; /* Error reported through db->mallocFailed */
671 memset(&a
[pParse
->nzVar
], 0, (x
-pParse
->nzVar
)*sizeof(a
[0]));
674 if( z
[0]!='?' || pParse
->azVar
[x
-1]==0 ){
675 sqlite3DbFree(db
, pParse
->azVar
[x
-1]);
676 pParse
->azVar
[x
-1] = sqlite3DbStrNDup(db
, z
, n
);
680 if( !pParse
->nErr
&& pParse
->nVar
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
681 sqlite3ErrorMsg(pParse
, "too many SQL variables");
686 ** Recursively delete an expression tree.
688 void sqlite3ExprDelete(sqlite3
*db
, Expr
*p
){
690 /* Sanity check: Assert that the IntValue is non-negative if it exists */
691 assert( !ExprHasProperty(p
, EP_IntValue
) || p
->u
.iValue
>=0 );
692 if( !ExprHasProperty(p
, EP_TokenOnly
) ){
693 /* The Expr.x union is never used at the same time as Expr.pRight */
694 assert( p
->x
.pList
==0 || p
->pRight
==0 );
695 sqlite3ExprDelete(db
, p
->pLeft
);
696 sqlite3ExprDelete(db
, p
->pRight
);
697 if( ExprHasProperty(p
, EP_MemToken
) ) sqlite3DbFree(db
, p
->u
.zToken
);
698 if( ExprHasProperty(p
, EP_xIsSelect
) ){
699 sqlite3SelectDelete(db
, p
->x
.pSelect
);
701 sqlite3ExprListDelete(db
, p
->x
.pList
);
704 if( !ExprHasProperty(p
, EP_Static
) ){
705 sqlite3DbFree(db
, p
);
710 ** Return the number of bytes allocated for the expression structure
711 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
712 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
714 static int exprStructSize(Expr
*p
){
715 if( ExprHasProperty(p
, EP_TokenOnly
) ) return EXPR_TOKENONLYSIZE
;
716 if( ExprHasProperty(p
, EP_Reduced
) ) return EXPR_REDUCEDSIZE
;
717 return EXPR_FULLSIZE
;
721 ** The dupedExpr*Size() routines each return the number of bytes required
722 ** to store a copy of an expression or expression tree. They differ in
723 ** how much of the tree is measured.
725 ** dupedExprStructSize() Size of only the Expr structure
726 ** dupedExprNodeSize() Size of Expr + space for token
727 ** dupedExprSize() Expr + token + subtree components
729 ***************************************************************************
731 ** The dupedExprStructSize() function returns two values OR-ed together:
732 ** (1) the space required for a copy of the Expr structure only and
733 ** (2) the EP_xxx flags that indicate what the structure size should be.
734 ** The return values is always one of:
737 ** EXPR_REDUCEDSIZE | EP_Reduced
738 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
740 ** The size of the structure can be found by masking the return value
741 ** of this routine with 0xfff. The flags can be found by masking the
742 ** return value with EP_Reduced|EP_TokenOnly.
744 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
745 ** (unreduced) Expr objects as they or originally constructed by the parser.
746 ** During expression analysis, extra information is computed and moved into
747 ** later parts of teh Expr object and that extra information might get chopped
748 ** off if the expression is reduced. Note also that it does not work to
749 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
750 ** to reduce a pristine expression tree from the parser. The implementation
751 ** of dupedExprStructSize() contain multiple assert() statements that attempt
752 ** to enforce this constraint.
754 static int dupedExprStructSize(Expr
*p
, int flags
){
756 assert( flags
==EXPRDUP_REDUCE
|| flags
==0 ); /* Only one flag value allowed */
757 assert( EXPR_FULLSIZE
<=0xfff );
758 assert( (0xfff & (EP_Reduced
|EP_TokenOnly
))==0 );
759 if( 0==(flags
&EXPRDUP_REDUCE
) ){
760 nSize
= EXPR_FULLSIZE
;
762 assert( !ExprHasProperty(p
, EP_TokenOnly
|EP_Reduced
) );
763 assert( !ExprHasProperty(p
, EP_FromJoin
) );
764 assert( !ExprHasProperty(p
, EP_MemToken
) );
765 assert( !ExprHasProperty(p
, EP_NoReduce
) );
766 if( p
->pLeft
|| p
->x
.pList
){
767 nSize
= EXPR_REDUCEDSIZE
| EP_Reduced
;
769 assert( p
->pRight
==0 );
770 nSize
= EXPR_TOKENONLYSIZE
| EP_TokenOnly
;
777 ** This function returns the space in bytes required to store the copy
778 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
779 ** string is defined.)
781 static int dupedExprNodeSize(Expr
*p
, int flags
){
782 int nByte
= dupedExprStructSize(p
, flags
) & 0xfff;
783 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
784 nByte
+= sqlite3Strlen30(p
->u
.zToken
)+1;
786 return ROUND8(nByte
);
790 ** Return the number of bytes required to create a duplicate of the
791 ** expression passed as the first argument. The second argument is a
792 ** mask containing EXPRDUP_XXX flags.
794 ** The value returned includes space to create a copy of the Expr struct
795 ** itself and the buffer referred to by Expr.u.zToken, if any.
797 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
798 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
799 ** and Expr.pRight variables (but not for any structures pointed to or
800 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
802 static int dupedExprSize(Expr
*p
, int flags
){
805 nByte
= dupedExprNodeSize(p
, flags
);
806 if( flags
&EXPRDUP_REDUCE
){
807 nByte
+= dupedExprSize(p
->pLeft
, flags
) + dupedExprSize(p
->pRight
, flags
);
814 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
815 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
816 ** to store the copy of expression p, the copies of p->u.zToken
817 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
818 ** if any. Before returning, *pzBuffer is set to the first byte past the
819 ** portion of the buffer copied into by this function.
821 static Expr
*exprDup(sqlite3
*db
, Expr
*p
, int flags
, u8
**pzBuffer
){
822 Expr
*pNew
= 0; /* Value to return */
824 const int isReduced
= (flags
&EXPRDUP_REDUCE
);
828 assert( pzBuffer
==0 || isReduced
);
830 /* Figure out where to write the new Expr structure. */
833 staticFlag
= EP_Static
;
835 zAlloc
= sqlite3DbMallocRaw(db
, dupedExprSize(p
, flags
));
837 pNew
= (Expr
*)zAlloc
;
840 /* Set nNewSize to the size allocated for the structure pointed to
841 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
842 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
843 ** by the copy of the p->u.zToken string (if any).
845 const unsigned nStructSize
= dupedExprStructSize(p
, flags
);
846 const int nNewSize
= nStructSize
& 0xfff;
848 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
849 nToken
= sqlite3Strlen30(p
->u
.zToken
) + 1;
854 assert( ExprHasProperty(p
, EP_Reduced
)==0 );
855 memcpy(zAlloc
, p
, nNewSize
);
857 int nSize
= exprStructSize(p
);
858 memcpy(zAlloc
, p
, nSize
);
859 memset(&zAlloc
[nSize
], 0, EXPR_FULLSIZE
-nSize
);
862 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
863 pNew
->flags
&= ~(EP_Reduced
|EP_TokenOnly
|EP_Static
|EP_MemToken
);
864 pNew
->flags
|= nStructSize
& (EP_Reduced
|EP_TokenOnly
);
865 pNew
->flags
|= staticFlag
;
867 /* Copy the p->u.zToken string, if any. */
869 char *zToken
= pNew
->u
.zToken
= (char*)&zAlloc
[nNewSize
];
870 memcpy(zToken
, p
->u
.zToken
, nToken
);
873 if( 0==((p
->flags
|pNew
->flags
) & EP_TokenOnly
) ){
874 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
875 if( ExprHasProperty(p
, EP_xIsSelect
) ){
876 pNew
->x
.pSelect
= sqlite3SelectDup(db
, p
->x
.pSelect
, isReduced
);
878 pNew
->x
.pList
= sqlite3ExprListDup(db
, p
->x
.pList
, isReduced
);
882 /* Fill in pNew->pLeft and pNew->pRight. */
883 if( ExprHasProperty(pNew
, EP_Reduced
|EP_TokenOnly
) ){
884 zAlloc
+= dupedExprNodeSize(p
, flags
);
885 if( ExprHasProperty(pNew
, EP_Reduced
) ){
886 pNew
->pLeft
= exprDup(db
, p
->pLeft
, EXPRDUP_REDUCE
, &zAlloc
);
887 pNew
->pRight
= exprDup(db
, p
->pRight
, EXPRDUP_REDUCE
, &zAlloc
);
893 if( !ExprHasProperty(p
, EP_TokenOnly
) ){
894 pNew
->pLeft
= sqlite3ExprDup(db
, p
->pLeft
, 0);
895 pNew
->pRight
= sqlite3ExprDup(db
, p
->pRight
, 0);
905 ** Create and return a deep copy of the object passed as the second
906 ** argument. If an OOM condition is encountered, NULL is returned
907 ** and the db->mallocFailed flag set.
909 #ifndef SQLITE_OMIT_CTE
910 static With
*withDup(sqlite3
*db
, With
*p
){
913 int nByte
= sizeof(*p
) + sizeof(p
->a
[0]) * (p
->nCte
-1);
914 pRet
= sqlite3DbMallocZero(db
, nByte
);
917 pRet
->nCte
= p
->nCte
;
918 for(i
=0; i
<p
->nCte
; i
++){
919 pRet
->a
[i
].pSelect
= sqlite3SelectDup(db
, p
->a
[i
].pSelect
, 0);
920 pRet
->a
[i
].pCols
= sqlite3ExprListDup(db
, p
->a
[i
].pCols
, 0);
921 pRet
->a
[i
].zName
= sqlite3DbStrDup(db
, p
->a
[i
].zName
);
928 # define withDup(x,y) 0
932 ** The following group of routines make deep copies of expressions,
933 ** expression lists, ID lists, and select statements. The copies can
934 ** be deleted (by being passed to their respective ...Delete() routines)
935 ** without effecting the originals.
937 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
938 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
939 ** by subsequent calls to sqlite*ListAppend() routines.
941 ** Any tables that the SrcList might point to are not duplicated.
943 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
944 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
945 ** truncated version of the usual Expr structure that will be stored as
946 ** part of the in-memory representation of the database schema.
948 Expr
*sqlite3ExprDup(sqlite3
*db
, Expr
*p
, int flags
){
949 return exprDup(db
, p
, flags
, 0);
951 ExprList
*sqlite3ExprListDup(sqlite3
*db
, ExprList
*p
, int flags
){
953 struct ExprList_item
*pItem
, *pOldItem
;
956 pNew
= sqlite3DbMallocRaw(db
, sizeof(*pNew
) );
957 if( pNew
==0 ) return 0;
958 pNew
->nExpr
= i
= p
->nExpr
;
959 if( (flags
& EXPRDUP_REDUCE
)==0 ) for(i
=1; i
<p
->nExpr
; i
+=i
){}
960 pNew
->a
= pItem
= sqlite3DbMallocRaw(db
, i
*sizeof(p
->a
[0]) );
962 sqlite3DbFree(db
, pNew
);
966 for(i
=0; i
<p
->nExpr
; i
++, pItem
++, pOldItem
++){
967 Expr
*pOldExpr
= pOldItem
->pExpr
;
968 pItem
->pExpr
= sqlite3ExprDup(db
, pOldExpr
, flags
);
969 pItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
970 pItem
->zSpan
= sqlite3DbStrDup(db
, pOldItem
->zSpan
);
971 pItem
->sortOrder
= pOldItem
->sortOrder
;
973 pItem
->bSpanIsTab
= pOldItem
->bSpanIsTab
;
974 pItem
->u
= pOldItem
->u
;
980 ** If cursors, triggers, views and subqueries are all omitted from
981 ** the build, then none of the following routines, except for
982 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
983 ** called with a NULL argument.
985 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
986 || !defined(SQLITE_OMIT_SUBQUERY)
987 SrcList
*sqlite3SrcListDup(sqlite3
*db
, SrcList
*p
, int flags
){
992 nByte
= sizeof(*p
) + (p
->nSrc
>0 ? sizeof(p
->a
[0]) * (p
->nSrc
-1) : 0);
993 pNew
= sqlite3DbMallocRaw(db
, nByte
);
994 if( pNew
==0 ) return 0;
995 pNew
->nSrc
= pNew
->nAlloc
= p
->nSrc
;
996 for(i
=0; i
<p
->nSrc
; i
++){
997 struct SrcList_item
*pNewItem
= &pNew
->a
[i
];
998 struct SrcList_item
*pOldItem
= &p
->a
[i
];
1000 pNewItem
->pSchema
= pOldItem
->pSchema
;
1001 pNewItem
->zDatabase
= sqlite3DbStrDup(db
, pOldItem
->zDatabase
);
1002 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1003 pNewItem
->zAlias
= sqlite3DbStrDup(db
, pOldItem
->zAlias
);
1004 pNewItem
->jointype
= pOldItem
->jointype
;
1005 pNewItem
->iCursor
= pOldItem
->iCursor
;
1006 pNewItem
->addrFillSub
= pOldItem
->addrFillSub
;
1007 pNewItem
->regReturn
= pOldItem
->regReturn
;
1008 pNewItem
->isCorrelated
= pOldItem
->isCorrelated
;
1009 pNewItem
->viaCoroutine
= pOldItem
->viaCoroutine
;
1010 pNewItem
->isRecursive
= pOldItem
->isRecursive
;
1011 pNewItem
->zIndex
= sqlite3DbStrDup(db
, pOldItem
->zIndex
);
1012 pNewItem
->notIndexed
= pOldItem
->notIndexed
;
1013 pNewItem
->pIndex
= pOldItem
->pIndex
;
1014 pTab
= pNewItem
->pTab
= pOldItem
->pTab
;
1018 pNewItem
->pSelect
= sqlite3SelectDup(db
, pOldItem
->pSelect
, flags
);
1019 pNewItem
->pOn
= sqlite3ExprDup(db
, pOldItem
->pOn
, flags
);
1020 pNewItem
->pUsing
= sqlite3IdListDup(db
, pOldItem
->pUsing
);
1021 pNewItem
->colUsed
= pOldItem
->colUsed
;
1025 IdList
*sqlite3IdListDup(sqlite3
*db
, IdList
*p
){
1028 if( p
==0 ) return 0;
1029 pNew
= sqlite3DbMallocRaw(db
, sizeof(*pNew
) );
1030 if( pNew
==0 ) return 0;
1032 pNew
->a
= sqlite3DbMallocRaw(db
, p
->nId
*sizeof(p
->a
[0]) );
1034 sqlite3DbFree(db
, pNew
);
1037 /* Note that because the size of the allocation for p->a[] is not
1038 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1039 ** on the duplicate created by this function. */
1040 for(i
=0; i
<p
->nId
; i
++){
1041 struct IdList_item
*pNewItem
= &pNew
->a
[i
];
1042 struct IdList_item
*pOldItem
= &p
->a
[i
];
1043 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1044 pNewItem
->idx
= pOldItem
->idx
;
1048 Select
*sqlite3SelectDup(sqlite3
*db
, Select
*p
, int flags
){
1049 Select
*pNew
, *pPrior
;
1050 if( p
==0 ) return 0;
1051 pNew
= sqlite3DbMallocRaw(db
, sizeof(*p
) );
1052 if( pNew
==0 ) return 0;
1053 pNew
->pEList
= sqlite3ExprListDup(db
, p
->pEList
, flags
);
1054 pNew
->pSrc
= sqlite3SrcListDup(db
, p
->pSrc
, flags
);
1055 pNew
->pWhere
= sqlite3ExprDup(db
, p
->pWhere
, flags
);
1056 pNew
->pGroupBy
= sqlite3ExprListDup(db
, p
->pGroupBy
, flags
);
1057 pNew
->pHaving
= sqlite3ExprDup(db
, p
->pHaving
, flags
);
1058 pNew
->pOrderBy
= sqlite3ExprListDup(db
, p
->pOrderBy
, flags
);
1060 pNew
->pPrior
= pPrior
= sqlite3SelectDup(db
, p
->pPrior
, flags
);
1061 if( pPrior
) pPrior
->pNext
= pNew
;
1063 pNew
->pLimit
= sqlite3ExprDup(db
, p
->pLimit
, flags
);
1064 pNew
->pOffset
= sqlite3ExprDup(db
, p
->pOffset
, flags
);
1067 pNew
->selFlags
= p
->selFlags
& ~SF_UsesEphemeral
;
1068 pNew
->addrOpenEphm
[0] = -1;
1069 pNew
->addrOpenEphm
[1] = -1;
1070 pNew
->nSelectRow
= p
->nSelectRow
;
1071 pNew
->pWith
= withDup(db
, p
->pWith
);
1072 sqlite3SelectSetName(pNew
, p
->zSelName
);
1076 Select
*sqlite3SelectDup(sqlite3
*db
, Select
*p
, int flags
){
1084 ** Add a new element to the end of an expression list. If pList is
1085 ** initially NULL, then create a new expression list.
1087 ** If a memory allocation error occurs, the entire list is freed and
1088 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1089 ** that the new entry was successfully appended.
1091 ExprList
*sqlite3ExprListAppend(
1092 Parse
*pParse
, /* Parsing context */
1093 ExprList
*pList
, /* List to which to append. Might be NULL */
1094 Expr
*pExpr
/* Expression to be appended. Might be NULL */
1096 sqlite3
*db
= pParse
->db
;
1098 pList
= sqlite3DbMallocZero(db
, sizeof(ExprList
) );
1102 pList
->a
= sqlite3DbMallocRaw(db
, sizeof(pList
->a
[0]));
1103 if( pList
->a
==0 ) goto no_mem
;
1104 }else if( (pList
->nExpr
& (pList
->nExpr
-1))==0 ){
1105 struct ExprList_item
*a
;
1106 assert( pList
->nExpr
>0 );
1107 a
= sqlite3DbRealloc(db
, pList
->a
, pList
->nExpr
*2*sizeof(pList
->a
[0]));
1113 assert( pList
->a
!=0 );
1115 struct ExprList_item
*pItem
= &pList
->a
[pList
->nExpr
++];
1116 memset(pItem
, 0, sizeof(*pItem
));
1117 pItem
->pExpr
= pExpr
;
1122 /* Avoid leaking memory if malloc has failed. */
1123 sqlite3ExprDelete(db
, pExpr
);
1124 sqlite3ExprListDelete(db
, pList
);
1129 ** Set the ExprList.a[].zName element of the most recently added item
1130 ** on the expression list.
1132 ** pList might be NULL following an OOM error. But pName should never be
1133 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1136 void sqlite3ExprListSetName(
1137 Parse
*pParse
, /* Parsing context */
1138 ExprList
*pList
, /* List to which to add the span. */
1139 Token
*pName
, /* Name to be added */
1140 int dequote
/* True to cause the name to be dequoted */
1142 assert( pList
!=0 || pParse
->db
->mallocFailed
!=0 );
1144 struct ExprList_item
*pItem
;
1145 assert( pList
->nExpr
>0 );
1146 pItem
= &pList
->a
[pList
->nExpr
-1];
1147 assert( pItem
->zName
==0 );
1148 pItem
->zName
= sqlite3DbStrNDup(pParse
->db
, pName
->z
, pName
->n
);
1149 if( dequote
&& pItem
->zName
) sqlite3Dequote(pItem
->zName
);
1154 ** Set the ExprList.a[].zSpan element of the most recently added item
1155 ** on the expression list.
1157 ** pList might be NULL following an OOM error. But pSpan should never be
1158 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1161 void sqlite3ExprListSetSpan(
1162 Parse
*pParse
, /* Parsing context */
1163 ExprList
*pList
, /* List to which to add the span. */
1164 ExprSpan
*pSpan
/* The span to be added */
1166 sqlite3
*db
= pParse
->db
;
1167 assert( pList
!=0 || db
->mallocFailed
!=0 );
1169 struct ExprList_item
*pItem
= &pList
->a
[pList
->nExpr
-1];
1170 assert( pList
->nExpr
>0 );
1171 assert( db
->mallocFailed
|| pItem
->pExpr
==pSpan
->pExpr
);
1172 sqlite3DbFree(db
, pItem
->zSpan
);
1173 pItem
->zSpan
= sqlite3DbStrNDup(db
, (char*)pSpan
->zStart
,
1174 (int)(pSpan
->zEnd
- pSpan
->zStart
));
1179 ** If the expression list pEList contains more than iLimit elements,
1180 ** leave an error message in pParse.
1182 void sqlite3ExprListCheckLength(
1187 int mx
= pParse
->db
->aLimit
[SQLITE_LIMIT_COLUMN
];
1188 testcase( pEList
&& pEList
->nExpr
==mx
);
1189 testcase( pEList
&& pEList
->nExpr
==mx
+1 );
1190 if( pEList
&& pEList
->nExpr
>mx
){
1191 sqlite3ErrorMsg(pParse
, "too many columns in %s", zObject
);
1196 ** Delete an entire expression list.
1198 void sqlite3ExprListDelete(sqlite3
*db
, ExprList
*pList
){
1200 struct ExprList_item
*pItem
;
1201 if( pList
==0 ) return;
1202 assert( pList
->a
!=0 || pList
->nExpr
==0 );
1203 for(pItem
=pList
->a
, i
=0; i
<pList
->nExpr
; i
++, pItem
++){
1204 sqlite3ExprDelete(db
, pItem
->pExpr
);
1205 sqlite3DbFree(db
, pItem
->zName
);
1206 sqlite3DbFree(db
, pItem
->zSpan
);
1208 sqlite3DbFree(db
, pList
->a
);
1209 sqlite3DbFree(db
, pList
);
1213 ** These routines are Walker callbacks. Walker.u.pi is a pointer
1214 ** to an integer. These routines are checking an expression to see
1215 ** if it is a constant. Set *Walker.u.i to 0 if the expression is
1218 ** These callback routines are used to implement the following:
1220 ** sqlite3ExprIsConstant() pWalker->u.i==1
1221 ** sqlite3ExprIsConstantNotJoin() pWalker->u.i==2
1222 ** sqlite3ExprIsConstantOrFunction() pWalker->u.i==3 or 4
1224 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
1225 ** in a CREATE TABLE statement. The Walker.u.i value is 4 when parsing
1226 ** an existing schema and 3 when processing a new statement. A bound
1227 ** parameter raises an error for new statements, but is silently converted
1228 ** to NULL for existing schemas. This allows sqlite_master tables that
1229 ** contain a bound parameter because they were generated by older versions
1230 ** of SQLite to be parsed by newer versions of SQLite without raising a
1231 ** malformed schema error.
1233 static int exprNodeIsConstant(Walker
*pWalker
, Expr
*pExpr
){
1235 /* If pWalker->u.i is 2 then any term of the expression that comes from
1236 ** the ON or USING clauses of a join disqualifies the expression
1237 ** from being considered constant. */
1238 if( pWalker
->u
.i
==2 && ExprHasProperty(pExpr
, EP_FromJoin
) ){
1243 switch( pExpr
->op
){
1244 /* Consider functions to be constant if all their arguments are constant
1245 ** and either pWalker->u.i==3 or 4 or the function as the SQLITE_FUNC_CONST
1248 if( pWalker
->u
.i
>=3 || ExprHasProperty(pExpr
,EP_Constant
) ){
1249 return WRC_Continue
;
1254 case TK_AGG_FUNCTION
:
1256 testcase( pExpr
->op
==TK_ID
);
1257 testcase( pExpr
->op
==TK_COLUMN
);
1258 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
1259 testcase( pExpr
->op
==TK_AGG_COLUMN
);
1263 if( pWalker
->u
.i
==4 ){
1264 /* Silently convert bound parameters that appear inside of CREATE
1265 ** statements into a NULL when parsing the CREATE statement text out
1266 ** of the sqlite_master table */
1267 pExpr
->op
= TK_NULL
;
1268 }else if( pWalker
->u
.i
==3 ){
1269 /* A bound parameter in a CREATE statement that originates from
1270 ** sqlite3_prepare() causes an error */
1276 testcase( pExpr
->op
==TK_SELECT
); /* selectNodeIsConstant will disallow */
1277 testcase( pExpr
->op
==TK_EXISTS
); /* selectNodeIsConstant will disallow */
1278 return WRC_Continue
;
1281 static int selectNodeIsConstant(Walker
*pWalker
, Select
*NotUsed
){
1282 UNUSED_PARAMETER(NotUsed
);
1286 static int exprIsConst(Expr
*p
, int initFlag
){
1288 memset(&w
, 0, sizeof(w
));
1290 w
.xExprCallback
= exprNodeIsConstant
;
1291 w
.xSelectCallback
= selectNodeIsConstant
;
1292 sqlite3WalkExpr(&w
, p
);
1297 ** Walk an expression tree. Return 1 if the expression is constant
1298 ** and 0 if it involves variables or function calls.
1300 ** For the purposes of this function, a double-quoted string (ex: "abc")
1301 ** is considered a variable but a single-quoted string (ex: 'abc') is
1304 int sqlite3ExprIsConstant(Expr
*p
){
1305 return exprIsConst(p
, 1);
1309 ** Walk an expression tree. Return 1 if the expression is constant
1310 ** that does no originate from the ON or USING clauses of a join.
1311 ** Return 0 if it involves variables or function calls or terms from
1312 ** an ON or USING clause.
1314 int sqlite3ExprIsConstantNotJoin(Expr
*p
){
1315 return exprIsConst(p
, 2);
1319 ** Walk an expression tree. Return 1 if the expression is constant
1320 ** or a function call with constant arguments. Return and 0 if there
1321 ** are any variables.
1323 ** For the purposes of this function, a double-quoted string (ex: "abc")
1324 ** is considered a variable but a single-quoted string (ex: 'abc') is
1327 int sqlite3ExprIsConstantOrFunction(Expr
*p
, u8 isInit
){
1328 assert( isInit
==0 || isInit
==1 );
1329 return exprIsConst(p
, 3+isInit
);
1333 ** If the expression p codes a constant integer that is small enough
1334 ** to fit in a 32-bit integer, return 1 and put the value of the integer
1335 ** in *pValue. If the expression is not an integer or if it is too big
1336 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1338 int sqlite3ExprIsInteger(Expr
*p
, int *pValue
){
1341 /* If an expression is an integer literal that fits in a signed 32-bit
1342 ** integer, then the EP_IntValue flag will have already been set */
1343 assert( p
->op
!=TK_INTEGER
|| (p
->flags
& EP_IntValue
)!=0
1344 || sqlite3GetInt32(p
->u
.zToken
, &rc
)==0 );
1346 if( p
->flags
& EP_IntValue
){
1347 *pValue
= p
->u
.iValue
;
1352 rc
= sqlite3ExprIsInteger(p
->pLeft
, pValue
);
1357 if( sqlite3ExprIsInteger(p
->pLeft
, &v
) ){
1358 assert( v
!=(-2147483647-1) );
1370 ** Return FALSE if there is no chance that the expression can be NULL.
1372 ** If the expression might be NULL or if the expression is too complex
1373 ** to tell return TRUE.
1375 ** This routine is used as an optimization, to skip OP_IsNull opcodes
1376 ** when we know that a value cannot be NULL. Hence, a false positive
1377 ** (returning TRUE when in fact the expression can never be NULL) might
1378 ** be a small performance hit but is otherwise harmless. On the other
1379 ** hand, a false negative (returning FALSE when the result could be NULL)
1380 ** will likely result in an incorrect answer. So when in doubt, return
1383 int sqlite3ExprCanBeNull(const Expr
*p
){
1385 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){ p
= p
->pLeft
; }
1387 if( op
==TK_REGISTER
) op
= p
->op2
;
1395 assert( p
->pTab
!=0 );
1396 return ExprHasProperty(p
, EP_CanBeNull
) ||
1397 (p
->iColumn
>=0 && p
->pTab
->aCol
[p
->iColumn
].notNull
==0);
1404 ** Return TRUE if the given expression is a constant which would be
1405 ** unchanged by OP_Affinity with the affinity given in the second
1408 ** This routine is used to determine if the OP_Affinity operation
1409 ** can be omitted. When in doubt return FALSE. A false negative
1410 ** is harmless. A false positive, however, can result in the wrong
1413 int sqlite3ExprNeedsNoAffinityChange(const Expr
*p
, char aff
){
1415 if( aff
==SQLITE_AFF_NONE
) return 1;
1416 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){ p
= p
->pLeft
; }
1418 if( op
==TK_REGISTER
) op
= p
->op2
;
1421 return aff
==SQLITE_AFF_INTEGER
|| aff
==SQLITE_AFF_NUMERIC
;
1424 return aff
==SQLITE_AFF_REAL
|| aff
==SQLITE_AFF_NUMERIC
;
1427 return aff
==SQLITE_AFF_TEXT
;
1433 assert( p
->iTable
>=0 ); /* p cannot be part of a CHECK constraint */
1435 && (aff
==SQLITE_AFF_INTEGER
|| aff
==SQLITE_AFF_NUMERIC
);
1444 ** Return TRUE if the given string is a row-id column name.
1446 int sqlite3IsRowid(const char *z
){
1447 if( sqlite3StrICmp(z
, "_ROWID_")==0 ) return 1;
1448 if( sqlite3StrICmp(z
, "ROWID")==0 ) return 1;
1449 if( sqlite3StrICmp(z
, "OID")==0 ) return 1;
1454 ** Return true if we are able to the IN operator optimization on a
1455 ** query of the form
1457 ** x IN (SELECT ...)
1459 ** Where the SELECT... clause is as specified by the parameter to this
1462 ** The Select object passed in has already been preprocessed and no
1463 ** errors have been found.
1465 #ifndef SQLITE_OMIT_SUBQUERY
1466 static int isCandidateForInOpt(Select
*p
){
1470 if( p
==0 ) return 0; /* right-hand side of IN is SELECT */
1471 if( p
->pPrior
) return 0; /* Not a compound SELECT */
1472 if( p
->selFlags
& (SF_Distinct
|SF_Aggregate
) ){
1473 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Distinct
);
1474 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Aggregate
);
1475 return 0; /* No DISTINCT keyword and no aggregate functions */
1477 assert( p
->pGroupBy
==0 ); /* Has no GROUP BY clause */
1478 if( p
->pLimit
) return 0; /* Has no LIMIT clause */
1479 assert( p
->pOffset
==0 ); /* No LIMIT means no OFFSET */
1480 if( p
->pWhere
) return 0; /* Has no WHERE clause */
1483 if( pSrc
->nSrc
!=1 ) return 0; /* Single term in FROM clause */
1484 if( pSrc
->a
[0].pSelect
) return 0; /* FROM is not a subquery or view */
1485 pTab
= pSrc
->a
[0].pTab
;
1486 if( NEVER(pTab
==0) ) return 0;
1487 assert( pTab
->pSelect
==0 ); /* FROM clause is not a view */
1488 if( IsVirtual(pTab
) ) return 0; /* FROM clause not a virtual table */
1490 if( pEList
->nExpr
!=1 ) return 0; /* One column in the result set */
1491 if( pEList
->a
[0].pExpr
->op
!=TK_COLUMN
) return 0; /* Result is a column */
1494 #endif /* SQLITE_OMIT_SUBQUERY */
1497 ** Code an OP_Once instruction and allocate space for its flag. Return the
1498 ** address of the new instruction.
1500 int sqlite3CodeOnce(Parse
*pParse
){
1501 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Virtual machine being coded */
1502 return sqlite3VdbeAddOp1(v
, OP_Once
, pParse
->nOnce
++);
1506 ** Generate code that checks the left-most column of index table iCur to see if
1507 ** it contains any NULL entries. Cause the register at regHasNull to be set
1508 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
1509 ** to be set to NULL if iCur contains one or more NULL values.
1511 static void sqlite3SetHasNullFlag(Vdbe
*v
, int iCur
, int regHasNull
){
1513 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regHasNull
);
1514 j1
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iCur
); VdbeCoverage(v
);
1515 sqlite3VdbeAddOp3(v
, OP_Column
, iCur
, 0, regHasNull
);
1516 sqlite3VdbeChangeP5(v
, OPFLAG_TYPEOFARG
);
1517 VdbeComment((v
, "first_entry_in(%d)", iCur
));
1518 sqlite3VdbeJumpHere(v
, j1
);
1522 #ifndef SQLITE_OMIT_SUBQUERY
1524 ** The argument is an IN operator with a list (not a subquery) on the
1525 ** right-hand side. Return TRUE if that list is constant.
1527 static int sqlite3InRhsIsConstant(Expr
*pIn
){
1530 assert( !ExprHasProperty(pIn
, EP_xIsSelect
) );
1533 res
= sqlite3ExprIsConstant(pIn
);
1540 ** This function is used by the implementation of the IN (...) operator.
1541 ** The pX parameter is the expression on the RHS of the IN operator, which
1542 ** might be either a list of expressions or a subquery.
1544 ** The job of this routine is to find or create a b-tree object that can
1545 ** be used either to test for membership in the RHS set or to iterate through
1546 ** all members of the RHS set, skipping duplicates.
1548 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
1549 ** and pX->iTable is set to the index of that cursor.
1551 ** The returned value of this function indicates the b-tree type, as follows:
1553 ** IN_INDEX_ROWID - The cursor was opened on a database table.
1554 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
1555 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
1556 ** IN_INDEX_EPH - The cursor was opened on a specially created and
1557 ** populated epheremal table.
1558 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
1559 ** implemented as a sequence of comparisons.
1561 ** An existing b-tree might be used if the RHS expression pX is a simple
1562 ** subquery such as:
1564 ** SELECT <column> FROM <table>
1566 ** If the RHS of the IN operator is a list or a more complex subquery, then
1567 ** an ephemeral table might need to be generated from the RHS and then
1568 ** pX->iTable made to point to the ephemeral table instead of an
1571 ** The inFlags parameter must contain exactly one of the bits
1572 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
1573 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
1574 ** fast membership test. When the IN_INDEX_LOOP bit is set, the
1575 ** IN index will be used to loop over all values of the RHS of the
1578 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
1579 ** through the set members) then the b-tree must not contain duplicates.
1580 ** An epheremal table must be used unless the selected <column> is guaranteed
1581 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
1582 ** has a UNIQUE constraint or UNIQUE index.
1584 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
1585 ** for fast set membership tests) then an epheremal table must
1586 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
1587 ** be found with <column> as its left-most column.
1589 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
1590 ** if the RHS of the IN operator is a list (not a subquery) then this
1591 ** routine might decide that creating an ephemeral b-tree for membership
1592 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
1593 ** calling routine should implement the IN operator using a sequence
1594 ** of Eq or Ne comparison operations.
1596 ** When the b-tree is being used for membership tests, the calling function
1597 ** might need to know whether or not the RHS side of the IN operator
1598 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
1599 ** if there is any chance that the (...) might contain a NULL value at
1600 ** runtime, then a register is allocated and the register number written
1601 ** to *prRhsHasNull. If there is no chance that the (...) contains a
1602 ** NULL value, then *prRhsHasNull is left unchanged.
1604 ** If a register is allocated and its location stored in *prRhsHasNull, then
1605 ** the value in that register will be NULL if the b-tree contains one or more
1606 ** NULL values, and it will be some non-NULL value if the b-tree contains no
1609 #ifndef SQLITE_OMIT_SUBQUERY
1610 int sqlite3FindInIndex(Parse
*pParse
, Expr
*pX
, u32 inFlags
, int *prRhsHasNull
){
1611 Select
*p
; /* SELECT to the right of IN operator */
1612 int eType
= 0; /* Type of RHS table. IN_INDEX_* */
1613 int iTab
= pParse
->nTab
++; /* Cursor of the RHS table */
1614 int mustBeUnique
; /* True if RHS must be unique */
1615 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Virtual machine being coded */
1617 assert( pX
->op
==TK_IN
);
1618 mustBeUnique
= (inFlags
& IN_INDEX_LOOP
)!=0;
1620 /* Check to see if an existing table or index can be used to
1621 ** satisfy the query. This is preferable to generating a new
1624 p
= (ExprHasProperty(pX
, EP_xIsSelect
) ? pX
->x
.pSelect
: 0);
1625 if( ALWAYS(pParse
->nErr
==0) && isCandidateForInOpt(p
) ){
1626 sqlite3
*db
= pParse
->db
; /* Database connection */
1627 Table
*pTab
; /* Table <table>. */
1628 Expr
*pExpr
; /* Expression <column> */
1629 i16 iCol
; /* Index of column <column> */
1630 i16 iDb
; /* Database idx for pTab */
1632 assert( p
); /* Because of isCandidateForInOpt(p) */
1633 assert( p
->pEList
!=0 ); /* Because of isCandidateForInOpt(p) */
1634 assert( p
->pEList
->a
[0].pExpr
!=0 ); /* Because of isCandidateForInOpt(p) */
1635 assert( p
->pSrc
!=0 ); /* Because of isCandidateForInOpt(p) */
1636 pTab
= p
->pSrc
->a
[0].pTab
;
1637 pExpr
= p
->pEList
->a
[0].pExpr
;
1638 iCol
= (i16
)pExpr
->iColumn
;
1640 /* Code an OP_Transaction and OP_TableLock for <table>. */
1641 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
1642 sqlite3CodeVerifySchema(pParse
, iDb
);
1643 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 0, pTab
->zName
);
1645 /* This function is only called from two places. In both cases the vdbe
1646 ** has already been allocated. So assume sqlite3GetVdbe() is always
1651 int iAddr
= sqlite3CodeOnce(pParse
);
1654 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
1655 eType
= IN_INDEX_ROWID
;
1657 sqlite3VdbeJumpHere(v
, iAddr
);
1659 Index
*pIdx
; /* Iterator variable */
1661 /* The collation sequence used by the comparison. If an index is to
1662 ** be used in place of a temp-table, it must be ordered according
1663 ** to this collation sequence. */
1664 CollSeq
*pReq
= sqlite3BinaryCompareCollSeq(pParse
, pX
->pLeft
, pExpr
);
1666 /* Check that the affinity that will be used to perform the
1667 ** comparison is the same as the affinity of the column. If
1668 ** it is not, it is not possible to use any index.
1670 int affinity_ok
= sqlite3IndexAffinityOk(pX
, pTab
->aCol
[iCol
].affinity
);
1672 for(pIdx
=pTab
->pIndex
; pIdx
&& eType
==0 && affinity_ok
; pIdx
=pIdx
->pNext
){
1673 if( (pIdx
->aiColumn
[0]==iCol
)
1674 && sqlite3FindCollSeq(db
, ENC(db
), pIdx
->azColl
[0], 0)==pReq
1675 && (!mustBeUnique
|| (pIdx
->nKeyCol
==1 && IsUniqueIndex(pIdx
)))
1677 int iAddr
= sqlite3CodeOnce(pParse
); VdbeCoverage(v
);
1678 sqlite3VdbeAddOp3(v
, OP_OpenRead
, iTab
, pIdx
->tnum
, iDb
);
1679 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
1680 VdbeComment((v
, "%s", pIdx
->zName
));
1681 assert( IN_INDEX_INDEX_DESC
== IN_INDEX_INDEX_ASC
+1 );
1682 eType
= IN_INDEX_INDEX_ASC
+ pIdx
->aSortOrder
[0];
1684 if( prRhsHasNull
&& !pTab
->aCol
[iCol
].notNull
){
1685 *prRhsHasNull
= ++pParse
->nMem
;
1686 sqlite3SetHasNullFlag(v
, iTab
, *prRhsHasNull
);
1688 sqlite3VdbeJumpHere(v
, iAddr
);
1694 /* If no preexisting index is available for the IN clause
1695 ** and IN_INDEX_NOOP is an allowed reply
1696 ** and the RHS of the IN operator is a list, not a subquery
1697 ** and the RHS is not contant or has two or fewer terms,
1698 ** then it is not worth creating an ephemeral table to evaluate
1699 ** the IN operator so return IN_INDEX_NOOP.
1702 && (inFlags
& IN_INDEX_NOOP_OK
)
1703 && !ExprHasProperty(pX
, EP_xIsSelect
)
1704 && (!sqlite3InRhsIsConstant(pX
) || pX
->x
.pList
->nExpr
<=2)
1706 eType
= IN_INDEX_NOOP
;
1711 /* Could not find an existing table or index to use as the RHS b-tree.
1712 ** We will have to generate an ephemeral table to do the job.
1714 u32 savedNQueryLoop
= pParse
->nQueryLoop
;
1715 int rMayHaveNull
= 0;
1716 eType
= IN_INDEX_EPH
;
1717 if( inFlags
& IN_INDEX_LOOP
){
1718 pParse
->nQueryLoop
= 0;
1719 if( pX
->pLeft
->iColumn
<0 && !ExprHasProperty(pX
, EP_xIsSelect
) ){
1720 eType
= IN_INDEX_ROWID
;
1722 }else if( prRhsHasNull
){
1723 *prRhsHasNull
= rMayHaveNull
= ++pParse
->nMem
;
1725 sqlite3CodeSubselect(pParse
, pX
, rMayHaveNull
, eType
==IN_INDEX_ROWID
);
1726 pParse
->nQueryLoop
= savedNQueryLoop
;
1735 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
1736 ** or IN operators. Examples:
1738 ** (SELECT a FROM b) -- subquery
1739 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
1740 ** x IN (4,5,11) -- IN operator with list on right-hand side
1741 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
1743 ** The pExpr parameter describes the expression that contains the IN
1744 ** operator or subquery.
1746 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
1747 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
1748 ** to some integer key column of a table B-Tree. In this case, use an
1749 ** intkey B-Tree to store the set of IN(...) values instead of the usual
1750 ** (slower) variable length keys B-Tree.
1752 ** If rMayHaveNull is non-zero, that means that the operation is an IN
1753 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
1754 ** All this routine does is initialize the register given by rMayHaveNull
1755 ** to NULL. Calling routines will take care of changing this register
1756 ** value to non-NULL if the RHS is NULL-free.
1758 ** For a SELECT or EXISTS operator, return the register that holds the
1759 ** result. For IN operators or if an error occurs, the return value is 0.
1761 #ifndef SQLITE_OMIT_SUBQUERY
1762 int sqlite3CodeSubselect(
1763 Parse
*pParse
, /* Parsing context */
1764 Expr
*pExpr
, /* The IN, SELECT, or EXISTS operator */
1765 int rHasNullFlag
, /* Register that records whether NULLs exist in RHS */
1766 int isRowid
/* If true, LHS of IN operator is a rowid */
1768 int jmpIfDynamic
= -1; /* One-time test address */
1769 int rReg
= 0; /* Register storing resulting */
1770 Vdbe
*v
= sqlite3GetVdbe(pParse
);
1771 if( NEVER(v
==0) ) return 0;
1772 sqlite3ExprCachePush(pParse
);
1774 /* This code must be run in its entirety every time it is encountered
1775 ** if any of the following is true:
1777 ** * The right-hand side is a correlated subquery
1778 ** * The right-hand side is an expression list containing variables
1779 ** * We are inside a trigger
1781 ** If all of the above are false, then we can run this code just once
1782 ** save the results, and reuse the same result on subsequent invocations.
1784 if( !ExprHasProperty(pExpr
, EP_VarSelect
) ){
1785 jmpIfDynamic
= sqlite3CodeOnce(pParse
); VdbeCoverage(v
);
1788 #ifndef SQLITE_OMIT_EXPLAIN
1789 if( pParse
->explain
==2 ){
1790 char *zMsg
= sqlite3MPrintf(
1791 pParse
->db
, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic
>=0?"":"CORRELATED ",
1792 pExpr
->op
==TK_IN
?"LIST":"SCALAR", pParse
->iNextSelectId
1794 sqlite3VdbeAddOp4(v
, OP_Explain
, pParse
->iSelectId
, 0, 0, zMsg
, P4_DYNAMIC
);
1798 switch( pExpr
->op
){
1800 char affinity
; /* Affinity of the LHS of the IN */
1801 int addr
; /* Address of OP_OpenEphemeral instruction */
1802 Expr
*pLeft
= pExpr
->pLeft
; /* the LHS of the IN operator */
1803 KeyInfo
*pKeyInfo
= 0; /* Key information */
1805 affinity
= sqlite3ExprAffinity(pLeft
);
1807 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1808 ** expression it is handled the same way. An ephemeral table is
1809 ** filled with single-field index keys representing the results
1810 ** from the SELECT or the <exprlist>.
1812 ** If the 'x' expression is a column value, or the SELECT...
1813 ** statement returns a column value, then the affinity of that
1814 ** column is used to build the index keys. If both 'x' and the
1815 ** SELECT... statement are columns, then numeric affinity is used
1816 ** if either column has NUMERIC or INTEGER affinity. If neither
1817 ** 'x' nor the SELECT... statement are columns, then numeric affinity
1820 pExpr
->iTable
= pParse
->nTab
++;
1821 addr
= sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pExpr
->iTable
, !isRowid
);
1822 pKeyInfo
= isRowid
? 0 : sqlite3KeyInfoAlloc(pParse
->db
, 1, 1);
1824 if( ExprHasProperty(pExpr
, EP_xIsSelect
) ){
1825 /* Case 1: expr IN (SELECT ...)
1827 ** Generate code to write the results of the select into the temporary
1828 ** table allocated and opened above.
1830 Select
*pSelect
= pExpr
->x
.pSelect
;
1835 sqlite3SelectDestInit(&dest
, SRT_Set
, pExpr
->iTable
);
1836 dest
.affSdst
= (u8
)affinity
;
1837 assert( (pExpr
->iTable
&0x0000FFFF)==pExpr
->iTable
);
1838 pSelect
->iLimit
= 0;
1839 testcase( pSelect
->selFlags
& SF_Distinct
);
1840 testcase( pKeyInfo
==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
1841 if( sqlite3Select(pParse
, pSelect
, &dest
) ){
1842 sqlite3KeyInfoUnref(pKeyInfo
);
1845 pEList
= pSelect
->pEList
;
1846 assert( pKeyInfo
!=0 ); /* OOM will cause exit after sqlite3Select() */
1847 assert( pEList
!=0 );
1848 assert( pEList
->nExpr
>0 );
1849 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
1850 pKeyInfo
->aColl
[0] = sqlite3BinaryCompareCollSeq(pParse
, pExpr
->pLeft
,
1851 pEList
->a
[0].pExpr
);
1852 }else if( ALWAYS(pExpr
->x
.pList
!=0) ){
1853 /* Case 2: expr IN (exprlist)
1855 ** For each expression, build an index key from the evaluation and
1856 ** store it in the temporary table. If <expr> is a column, then use
1857 ** that columns affinity when building index keys. If <expr> is not
1858 ** a column, use numeric affinity.
1861 ExprList
*pList
= pExpr
->x
.pList
;
1862 struct ExprList_item
*pItem
;
1866 affinity
= SQLITE_AFF_NONE
;
1869 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
1870 pKeyInfo
->aColl
[0] = sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
1873 /* Loop through each expression in <exprlist>. */
1874 r1
= sqlite3GetTempReg(pParse
);
1875 r2
= sqlite3GetTempReg(pParse
);
1876 if( isRowid
) sqlite3VdbeAddOp2(v
, OP_Null
, 0, r2
);
1877 for(i
=pList
->nExpr
, pItem
=pList
->a
; i
>0; i
--, pItem
++){
1878 Expr
*pE2
= pItem
->pExpr
;
1881 /* If the expression is not constant then we will need to
1882 ** disable the test that was generated above that makes sure
1883 ** this code only executes once. Because for a non-constant
1884 ** expression we need to rerun this code each time.
1886 if( jmpIfDynamic
>=0 && !sqlite3ExprIsConstant(pE2
) ){
1887 sqlite3VdbeChangeToNoop(v
, jmpIfDynamic
);
1891 /* Evaluate the expression and insert it into the temp table */
1892 if( isRowid
&& sqlite3ExprIsInteger(pE2
, &iValToIns
) ){
1893 sqlite3VdbeAddOp3(v
, OP_InsertInt
, pExpr
->iTable
, r2
, iValToIns
);
1895 r3
= sqlite3ExprCodeTarget(pParse
, pE2
, r1
);
1897 sqlite3VdbeAddOp2(v
, OP_MustBeInt
, r3
,
1898 sqlite3VdbeCurrentAddr(v
)+2);
1900 sqlite3VdbeAddOp3(v
, OP_Insert
, pExpr
->iTable
, r2
, r3
);
1902 sqlite3VdbeAddOp4(v
, OP_MakeRecord
, r3
, 1, r2
, &affinity
, 1);
1903 sqlite3ExprCacheAffinityChange(pParse
, r3
, 1);
1904 sqlite3VdbeAddOp2(v
, OP_IdxInsert
, pExpr
->iTable
, r2
);
1908 sqlite3ReleaseTempReg(pParse
, r1
);
1909 sqlite3ReleaseTempReg(pParse
, r2
);
1912 sqlite3VdbeChangeP4(v
, addr
, (void *)pKeyInfo
, P4_KEYINFO
);
1920 /* If this has to be a scalar SELECT. Generate code to put the
1921 ** value of this select in a memory cell and record the number
1922 ** of the memory cell in iColumn. If this is an EXISTS, write
1923 ** an integer 0 (not exists) or 1 (exists) into a memory cell
1924 ** and record that memory cell in iColumn.
1926 Select
*pSel
; /* SELECT statement to encode */
1927 SelectDest dest
; /* How to deal with SELECt result */
1929 testcase( pExpr
->op
==TK_EXISTS
);
1930 testcase( pExpr
->op
==TK_SELECT
);
1931 assert( pExpr
->op
==TK_EXISTS
|| pExpr
->op
==TK_SELECT
);
1933 assert( ExprHasProperty(pExpr
, EP_xIsSelect
) );
1934 pSel
= pExpr
->x
.pSelect
;
1935 sqlite3SelectDestInit(&dest
, 0, ++pParse
->nMem
);
1936 if( pExpr
->op
==TK_SELECT
){
1937 dest
.eDest
= SRT_Mem
;
1938 dest
.iSdst
= dest
.iSDParm
;
1939 sqlite3VdbeAddOp2(v
, OP_Null
, 0, dest
.iSDParm
);
1940 VdbeComment((v
, "Init subquery result"));
1942 dest
.eDest
= SRT_Exists
;
1943 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
.iSDParm
);
1944 VdbeComment((v
, "Init EXISTS result"));
1946 sqlite3ExprDelete(pParse
->db
, pSel
->pLimit
);
1947 pSel
->pLimit
= sqlite3PExpr(pParse
, TK_INTEGER
, 0, 0,
1948 &sqlite3IntTokens
[1]);
1950 if( sqlite3Select(pParse
, pSel
, &dest
) ){
1953 rReg
= dest
.iSDParm
;
1954 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
1960 sqlite3SetHasNullFlag(v
, pExpr
->iTable
, rHasNullFlag
);
1963 if( jmpIfDynamic
>=0 ){
1964 sqlite3VdbeJumpHere(v
, jmpIfDynamic
);
1966 sqlite3ExprCachePop(pParse
);
1970 #endif /* SQLITE_OMIT_SUBQUERY */
1972 #ifndef SQLITE_OMIT_SUBQUERY
1974 ** Generate code for an IN expression.
1976 ** x IN (SELECT ...)
1977 ** x IN (value, value, ...)
1979 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
1980 ** is an array of zero or more values. The expression is true if the LHS is
1981 ** contained within the RHS. The value of the expression is unknown (NULL)
1982 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
1983 ** RHS contains one or more NULL values.
1985 ** This routine generates code that jumps to destIfFalse if the LHS is not
1986 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
1987 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
1988 ** within the RHS then fall through.
1990 static void sqlite3ExprCodeIN(
1991 Parse
*pParse
, /* Parsing and code generating context */
1992 Expr
*pExpr
, /* The IN expression */
1993 int destIfFalse
, /* Jump here if LHS is not contained in the RHS */
1994 int destIfNull
/* Jump here if the results are unknown due to NULLs */
1996 int rRhsHasNull
= 0; /* Register that is true if RHS contains NULL values */
1997 char affinity
; /* Comparison affinity to use */
1998 int eType
; /* Type of the RHS */
1999 int r1
; /* Temporary use register */
2000 Vdbe
*v
; /* Statement under construction */
2002 /* Compute the RHS. After this step, the table with cursor
2003 ** pExpr->iTable will contains the values that make up the RHS.
2006 assert( v
!=0 ); /* OOM detected prior to this routine */
2007 VdbeNoopComment((v
, "begin IN expr"));
2008 eType
= sqlite3FindInIndex(pParse
, pExpr
,
2009 IN_INDEX_MEMBERSHIP
| IN_INDEX_NOOP_OK
,
2010 destIfFalse
==destIfNull
? 0 : &rRhsHasNull
);
2012 /* Figure out the affinity to use to create a key from the results
2013 ** of the expression. affinityStr stores a static string suitable for
2014 ** P4 of OP_MakeRecord.
2016 affinity
= comparisonAffinity(pExpr
);
2018 /* Code the LHS, the <expr> from "<expr> IN (...)".
2020 sqlite3ExprCachePush(pParse
);
2021 r1
= sqlite3GetTempReg(pParse
);
2022 sqlite3ExprCode(pParse
, pExpr
->pLeft
, r1
);
2024 /* If sqlite3FindInIndex() did not find or create an index that is
2025 ** suitable for evaluating the IN operator, then evaluate using a
2026 ** sequence of comparisons.
2028 if( eType
==IN_INDEX_NOOP
){
2029 ExprList
*pList
= pExpr
->x
.pList
;
2030 CollSeq
*pColl
= sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
2031 int labelOk
= sqlite3VdbeMakeLabel(v
);
2035 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
2036 if( destIfNull
!=destIfFalse
){
2037 regCkNull
= sqlite3GetTempReg(pParse
);
2038 sqlite3VdbeAddOp3(v
, OP_BitAnd
, r1
, r1
, regCkNull
);
2040 for(ii
=0; ii
<pList
->nExpr
; ii
++){
2041 r2
= sqlite3ExprCodeTemp(pParse
, pList
->a
[ii
].pExpr
, ®ToFree
);
2042 if( regCkNull
&& sqlite3ExprCanBeNull(pList
->a
[ii
].pExpr
) ){
2043 sqlite3VdbeAddOp3(v
, OP_BitAnd
, regCkNull
, r2
, regCkNull
);
2045 if( ii
<pList
->nExpr
-1 || destIfNull
!=destIfFalse
){
2046 sqlite3VdbeAddOp4(v
, OP_Eq
, r1
, labelOk
, r2
,
2047 (void*)pColl
, P4_COLLSEQ
);
2048 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1);
2049 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1);
2050 sqlite3VdbeChangeP5(v
, affinity
);
2052 assert( destIfNull
==destIfFalse
);
2053 sqlite3VdbeAddOp4(v
, OP_Ne
, r1
, destIfFalse
, r2
,
2054 (void*)pColl
, P4_COLLSEQ
); VdbeCoverage(v
);
2055 sqlite3VdbeChangeP5(v
, affinity
| SQLITE_JUMPIFNULL
);
2057 sqlite3ReleaseTempReg(pParse
, regToFree
);
2060 sqlite3VdbeAddOp2(v
, OP_IsNull
, regCkNull
, destIfNull
); VdbeCoverage(v
);
2061 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfFalse
);
2063 sqlite3VdbeResolveLabel(v
, labelOk
);
2064 sqlite3ReleaseTempReg(pParse
, regCkNull
);
2067 /* If the LHS is NULL, then the result is either false or NULL depending
2068 ** on whether the RHS is empty or not, respectively.
2070 if( sqlite3ExprCanBeNull(pExpr
->pLeft
) ){
2071 if( destIfNull
==destIfFalse
){
2072 /* Shortcut for the common case where the false and NULL outcomes are
2074 sqlite3VdbeAddOp2(v
, OP_IsNull
, r1
, destIfNull
); VdbeCoverage(v
);
2076 int addr1
= sqlite3VdbeAddOp1(v
, OP_NotNull
, r1
); VdbeCoverage(v
);
2077 sqlite3VdbeAddOp2(v
, OP_Rewind
, pExpr
->iTable
, destIfFalse
);
2079 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfNull
);
2080 sqlite3VdbeJumpHere(v
, addr1
);
2084 if( eType
==IN_INDEX_ROWID
){
2085 /* In this case, the RHS is the ROWID of table b-tree
2087 sqlite3VdbeAddOp2(v
, OP_MustBeInt
, r1
, destIfFalse
); VdbeCoverage(v
);
2088 sqlite3VdbeAddOp3(v
, OP_NotExists
, pExpr
->iTable
, destIfFalse
, r1
);
2091 /* In this case, the RHS is an index b-tree.
2093 sqlite3VdbeAddOp4(v
, OP_Affinity
, r1
, 1, 0, &affinity
, 1);
2095 /* If the set membership test fails, then the result of the
2096 ** "x IN (...)" expression must be either 0 or NULL. If the set
2097 ** contains no NULL values, then the result is 0. If the set
2098 ** contains one or more NULL values, then the result of the
2099 ** expression is also NULL.
2101 assert( destIfFalse
!=destIfNull
|| rRhsHasNull
==0 );
2102 if( rRhsHasNull
==0 ){
2103 /* This branch runs if it is known at compile time that the RHS
2104 ** cannot contain NULL values. This happens as the result
2105 ** of a "NOT NULL" constraint in the database schema.
2107 ** Also run this branch if NULL is equivalent to FALSE
2108 ** for this particular IN operator.
2110 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, pExpr
->iTable
, destIfFalse
, r1
, 1);
2113 /* In this branch, the RHS of the IN might contain a NULL and
2114 ** the presence of a NULL on the RHS makes a difference in the
2119 /* First check to see if the LHS is contained in the RHS. If so,
2120 ** then the answer is TRUE the presence of NULLs in the RHS does
2121 ** not matter. If the LHS is not contained in the RHS, then the
2122 ** answer is NULL if the RHS contains NULLs and the answer is
2123 ** FALSE if the RHS is NULL-free.
2125 j1
= sqlite3VdbeAddOp4Int(v
, OP_Found
, pExpr
->iTable
, 0, r1
, 1);
2127 sqlite3VdbeAddOp2(v
, OP_IsNull
, rRhsHasNull
, destIfNull
);
2129 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfFalse
);
2130 sqlite3VdbeJumpHere(v
, j1
);
2134 sqlite3ReleaseTempReg(pParse
, r1
);
2135 sqlite3ExprCachePop(pParse
);
2136 VdbeComment((v
, "end IN expr"));
2138 #endif /* SQLITE_OMIT_SUBQUERY */
2141 ** Duplicate an 8-byte value
2143 static char *dup8bytes(Vdbe
*v
, const char *in
){
2144 char *out
= sqlite3DbMallocRaw(sqlite3VdbeDb(v
), 8);
2151 #ifndef SQLITE_OMIT_FLOATING_POINT
2153 ** Generate an instruction that will put the floating point
2154 ** value described by z[0..n-1] into register iMem.
2156 ** The z[] string will probably not be zero-terminated. But the
2157 ** z[n] character is guaranteed to be something that does not look
2158 ** like the continuation of the number.
2160 static void codeReal(Vdbe
*v
, const char *z
, int negateFlag
, int iMem
){
2164 sqlite3AtoF(z
, &value
, sqlite3Strlen30(z
), SQLITE_UTF8
);
2165 assert( !sqlite3IsNaN(value
) ); /* The new AtoF never returns NaN */
2166 if( negateFlag
) value
= -value
;
2167 zV
= dup8bytes(v
, (char*)&value
);
2168 sqlite3VdbeAddOp4(v
, OP_Real
, 0, iMem
, 0, zV
, P4_REAL
);
2175 ** Generate an instruction that will put the integer describe by
2176 ** text z[0..n-1] into register iMem.
2178 ** Expr.u.zToken is always UTF8 and zero-terminated.
2180 static void codeInteger(Parse
*pParse
, Expr
*pExpr
, int negFlag
, int iMem
){
2181 Vdbe
*v
= pParse
->pVdbe
;
2182 if( pExpr
->flags
& EP_IntValue
){
2183 int i
= pExpr
->u
.iValue
;
2185 if( negFlag
) i
= -i
;
2186 sqlite3VdbeAddOp2(v
, OP_Integer
, i
, iMem
);
2190 const char *z
= pExpr
->u
.zToken
;
2192 c
= sqlite3DecOrHexToI64(z
, &value
);
2193 if( c
==0 || (c
==2 && negFlag
) ){
2195 if( negFlag
){ value
= c
==2 ? SMALLEST_INT64
: -value
; }
2196 zV
= dup8bytes(v
, (char*)&value
);
2197 sqlite3VdbeAddOp4(v
, OP_Int64
, 0, iMem
, 0, zV
, P4_INT64
);
2199 #ifdef SQLITE_OMIT_FLOATING_POINT
2200 sqlite3ErrorMsg(pParse
, "oversized integer: %s%s", negFlag
? "-" : "", z
);
2202 #ifndef SQLITE_OMIT_HEX_INTEGER
2203 if( sqlite3_strnicmp(z
,"0x",2)==0 ){
2204 sqlite3ErrorMsg(pParse
, "hex literal too big: %s", z
);
2208 codeReal(v
, z
, negFlag
, iMem
);
2216 ** Clear a cache entry.
2218 static void cacheEntryClear(Parse
*pParse
, struct yColCache
*p
){
2220 if( pParse
->nTempReg
<ArraySize(pParse
->aTempReg
) ){
2221 pParse
->aTempReg
[pParse
->nTempReg
++] = p
->iReg
;
2229 ** Record in the column cache that a particular column from a
2230 ** particular table is stored in a particular register.
2232 void sqlite3ExprCacheStore(Parse
*pParse
, int iTab
, int iCol
, int iReg
){
2236 struct yColCache
*p
;
2238 assert( iReg
>0 ); /* Register numbers are always positive */
2239 assert( iCol
>=-1 && iCol
<32768 ); /* Finite column numbers */
2241 /* The SQLITE_ColumnCache flag disables the column cache. This is used
2242 ** for testing only - to verify that SQLite always gets the same answer
2243 ** with and without the column cache.
2245 if( OptimizationDisabled(pParse
->db
, SQLITE_ColumnCache
) ) return;
2247 /* First replace any existing entry.
2249 ** Actually, the way the column cache is currently used, we are guaranteed
2250 ** that the object will never already be in cache. Verify this guarantee.
2253 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2254 assert( p
->iReg
==0 || p
->iTable
!=iTab
|| p
->iColumn
!=iCol
);
2258 /* Find an empty slot and replace it */
2259 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2261 p
->iLevel
= pParse
->iCacheLevel
;
2266 p
->lru
= pParse
->iCacheCnt
++;
2271 /* Replace the last recently used */
2272 minLru
= 0x7fffffff;
2274 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2275 if( p
->lru
<minLru
){
2280 if( ALWAYS(idxLru
>=0) ){
2281 p
= &pParse
->aColCache
[idxLru
];
2282 p
->iLevel
= pParse
->iCacheLevel
;
2287 p
->lru
= pParse
->iCacheCnt
++;
2293 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2294 ** Purge the range of registers from the column cache.
2296 void sqlite3ExprCacheRemove(Parse
*pParse
, int iReg
, int nReg
){
2298 int iLast
= iReg
+ nReg
- 1;
2299 struct yColCache
*p
;
2300 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2302 if( r
>=iReg
&& r
<=iLast
){
2303 cacheEntryClear(pParse
, p
);
2310 ** Remember the current column cache context. Any new entries added
2311 ** added to the column cache after this call are removed when the
2312 ** corresponding pop occurs.
2314 void sqlite3ExprCachePush(Parse
*pParse
){
2315 pParse
->iCacheLevel
++;
2317 if( pParse
->db
->flags
& SQLITE_VdbeAddopTrace
){
2318 printf("PUSH to %d\n", pParse
->iCacheLevel
);
2324 ** Remove from the column cache any entries that were added since the
2325 ** the previous sqlite3ExprCachePush operation. In other words, restore
2326 ** the cache to the state it was in prior the most recent Push.
2328 void sqlite3ExprCachePop(Parse
*pParse
){
2330 struct yColCache
*p
;
2331 assert( pParse
->iCacheLevel
>=1 );
2332 pParse
->iCacheLevel
--;
2334 if( pParse
->db
->flags
& SQLITE_VdbeAddopTrace
){
2335 printf("POP to %d\n", pParse
->iCacheLevel
);
2338 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2339 if( p
->iReg
&& p
->iLevel
>pParse
->iCacheLevel
){
2340 cacheEntryClear(pParse
, p
);
2347 ** When a cached column is reused, make sure that its register is
2348 ** no longer available as a temp register. ticket #3879: that same
2349 ** register might be in the cache in multiple places, so be sure to
2352 static void sqlite3ExprCachePinRegister(Parse
*pParse
, int iReg
){
2354 struct yColCache
*p
;
2355 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2356 if( p
->iReg
==iReg
){
2363 ** Generate code to extract the value of the iCol-th column of a table.
2365 void sqlite3ExprCodeGetColumnOfTable(
2366 Vdbe
*v
, /* The VDBE under construction */
2367 Table
*pTab
, /* The table containing the value */
2368 int iTabCur
, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
2369 int iCol
, /* Index of the column to extract */
2370 int regOut
/* Extract the value into this register */
2372 if( iCol
<0 || iCol
==pTab
->iPKey
){
2373 sqlite3VdbeAddOp2(v
, OP_Rowid
, iTabCur
, regOut
);
2375 int op
= IsVirtual(pTab
) ? OP_VColumn
: OP_Column
;
2377 if( !HasRowid(pTab
) ){
2378 x
= sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab
), iCol
);
2380 sqlite3VdbeAddOp3(v
, op
, iTabCur
, x
, regOut
);
2383 sqlite3ColumnDefault(v
, pTab
, iCol
, regOut
);
2388 ** Generate code that will extract the iColumn-th column from
2389 ** table pTab and store the column value in a register. An effort
2390 ** is made to store the column value in register iReg, but this is
2391 ** not guaranteed. The location of the column value is returned.
2393 ** There must be an open cursor to pTab in iTable when this routine
2394 ** is called. If iColumn<0 then code is generated that extracts the rowid.
2396 int sqlite3ExprCodeGetColumn(
2397 Parse
*pParse
, /* Parsing and code generating context */
2398 Table
*pTab
, /* Description of the table we are reading from */
2399 int iColumn
, /* Index of the table column */
2400 int iTable
, /* The cursor pointing to the table */
2401 int iReg
, /* Store results here */
2402 u8 p5
/* P5 value for OP_Column */
2404 Vdbe
*v
= pParse
->pVdbe
;
2406 struct yColCache
*p
;
2408 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2409 if( p
->iReg
>0 && p
->iTable
==iTable
&& p
->iColumn
==iColumn
){
2410 p
->lru
= pParse
->iCacheCnt
++;
2411 sqlite3ExprCachePinRegister(pParse
, p
->iReg
);
2416 sqlite3ExprCodeGetColumnOfTable(v
, pTab
, iTable
, iColumn
, iReg
);
2418 sqlite3VdbeChangeP5(v
, p5
);
2420 sqlite3ExprCacheStore(pParse
, iTable
, iColumn
, iReg
);
2426 ** Clear all column cache entries.
2428 void sqlite3ExprCacheClear(Parse
*pParse
){
2430 struct yColCache
*p
;
2433 if( pParse
->db
->flags
& SQLITE_VdbeAddopTrace
){
2437 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2439 cacheEntryClear(pParse
, p
);
2446 ** Record the fact that an affinity change has occurred on iCount
2447 ** registers starting with iStart.
2449 void sqlite3ExprCacheAffinityChange(Parse
*pParse
, int iStart
, int iCount
){
2450 sqlite3ExprCacheRemove(pParse
, iStart
, iCount
);
2454 ** Generate code to move content from registers iFrom...iFrom+nReg-1
2455 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
2457 void sqlite3ExprCodeMove(Parse
*pParse
, int iFrom
, int iTo
, int nReg
){
2458 assert( iFrom
>=iTo
+nReg
|| iFrom
+nReg
<=iTo
);
2459 sqlite3VdbeAddOp3(pParse
->pVdbe
, OP_Move
, iFrom
, iTo
, nReg
);
2460 sqlite3ExprCacheRemove(pParse
, iFrom
, nReg
);
2463 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
2465 ** Return true if any register in the range iFrom..iTo (inclusive)
2466 ** is used as part of the column cache.
2468 ** This routine is used within assert() and testcase() macros only
2469 ** and does not appear in a normal build.
2471 static int usedAsColumnCache(Parse
*pParse
, int iFrom
, int iTo
){
2473 struct yColCache
*p
;
2474 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
2476 if( r
>=iFrom
&& r
<=iTo
) return 1; /*NO_TEST*/
2480 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
2483 ** Convert an expression node to a TK_REGISTER
2485 static void exprToRegister(Expr
*p
, int iReg
){
2487 p
->op
= TK_REGISTER
;
2489 ExprClearProperty(p
, EP_Skip
);
2493 ** Generate code into the current Vdbe to evaluate the given
2494 ** expression. Attempt to store the results in register "target".
2495 ** Return the register where results are stored.
2497 ** With this routine, there is no guarantee that results will
2498 ** be stored in target. The result might be stored in some other
2499 ** register if it is convenient to do so. The calling function
2500 ** must check the return code and move the results to the desired
2503 int sqlite3ExprCodeTarget(Parse
*pParse
, Expr
*pExpr
, int target
){
2504 Vdbe
*v
= pParse
->pVdbe
; /* The VM under construction */
2505 int op
; /* The opcode being coded */
2506 int inReg
= target
; /* Results stored in register inReg */
2507 int regFree1
= 0; /* If non-zero free this temporary register */
2508 int regFree2
= 0; /* If non-zero free this temporary register */
2509 int r1
, r2
, r3
, r4
; /* Various register numbers */
2510 sqlite3
*db
= pParse
->db
; /* The database connection */
2511 Expr tempX
; /* Temporary expression node */
2513 assert( target
>0 && target
<=pParse
->nMem
);
2515 assert( pParse
->db
->mallocFailed
);
2525 case TK_AGG_COLUMN
: {
2526 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
2527 struct AggInfo_col
*pCol
= &pAggInfo
->aCol
[pExpr
->iAgg
];
2528 if( !pAggInfo
->directMode
){
2529 assert( pCol
->iMem
>0 );
2532 }else if( pAggInfo
->useSortingIdx
){
2533 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
2534 pCol
->iSorterColumn
, target
);
2537 /* Otherwise, fall thru into the TK_COLUMN case */
2540 int iTab
= pExpr
->iTable
;
2542 if( pParse
->ckBase
>0 ){
2543 /* Generating CHECK constraints or inserting into partial index */
2544 inReg
= pExpr
->iColumn
+ pParse
->ckBase
;
2547 /* Deleting from a partial index */
2548 iTab
= pParse
->iPartIdxTab
;
2551 inReg
= sqlite3ExprCodeGetColumn(pParse
, pExpr
->pTab
,
2552 pExpr
->iColumn
, iTab
, target
,
2557 codeInteger(pParse
, pExpr
, 0, target
);
2560 #ifndef SQLITE_OMIT_FLOATING_POINT
2562 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2563 codeReal(v
, pExpr
->u
.zToken
, 0, target
);
2568 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2569 sqlite3VdbeAddOp4(v
, OP_String8
, 0, target
, 0, pExpr
->u
.zToken
, 0);
2573 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
2576 #ifndef SQLITE_OMIT_BLOB_LITERAL
2581 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2582 assert( pExpr
->u
.zToken
[0]=='x' || pExpr
->u
.zToken
[0]=='X' );
2583 assert( pExpr
->u
.zToken
[1]=='\'' );
2584 z
= &pExpr
->u
.zToken
[2];
2585 n
= sqlite3Strlen30(z
) - 1;
2586 assert( z
[n
]=='\'' );
2587 zBlob
= sqlite3HexToBlob(sqlite3VdbeDb(v
), z
, n
);
2588 sqlite3VdbeAddOp4(v
, OP_Blob
, n
/2, target
, 0, zBlob
, P4_DYNAMIC
);
2593 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2594 assert( pExpr
->u
.zToken
!=0 );
2595 assert( pExpr
->u
.zToken
[0]!=0 );
2596 sqlite3VdbeAddOp2(v
, OP_Variable
, pExpr
->iColumn
, target
);
2597 if( pExpr
->u
.zToken
[1]!=0 ){
2598 assert( pExpr
->u
.zToken
[0]=='?'
2599 || strcmp(pExpr
->u
.zToken
, pParse
->azVar
[pExpr
->iColumn
-1])==0 );
2600 sqlite3VdbeChangeP4(v
, -1, pParse
->azVar
[pExpr
->iColumn
-1], P4_STATIC
);
2605 inReg
= pExpr
->iTable
;
2609 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
, target
);
2612 #ifndef SQLITE_OMIT_CAST
2614 /* Expressions of the form: CAST(pLeft AS token) */
2615 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
, target
);
2616 if( inReg
!=target
){
2617 sqlite3VdbeAddOp2(v
, OP_SCopy
, inReg
, target
);
2620 sqlite3VdbeAddOp2(v
, OP_Cast
, target
,
2621 sqlite3AffinityType(pExpr
->u
.zToken
, 0));
2622 testcase( usedAsColumnCache(pParse
, inReg
, inReg
) );
2623 sqlite3ExprCacheAffinityChange(pParse
, inReg
, 1);
2626 #endif /* SQLITE_OMIT_CAST */
2633 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
2634 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
2635 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
2636 r1
, r2
, inReg
, SQLITE_STOREP2
);
2637 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
2638 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
2639 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
2640 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
2641 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
2642 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
2643 testcase( regFree1
==0 );
2644 testcase( regFree2
==0 );
2649 testcase( op
==TK_IS
);
2650 testcase( op
==TK_ISNOT
);
2651 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
2652 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
2653 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
2654 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
2655 r1
, r2
, inReg
, SQLITE_STOREP2
| SQLITE_NULLEQ
);
2656 VdbeCoverageIf(v
, op
==TK_EQ
);
2657 VdbeCoverageIf(v
, op
==TK_NE
);
2658 testcase( regFree1
==0 );
2659 testcase( regFree2
==0 );
2674 assert( TK_AND
==OP_And
); testcase( op
==TK_AND
);
2675 assert( TK_OR
==OP_Or
); testcase( op
==TK_OR
);
2676 assert( TK_PLUS
==OP_Add
); testcase( op
==TK_PLUS
);
2677 assert( TK_MINUS
==OP_Subtract
); testcase( op
==TK_MINUS
);
2678 assert( TK_REM
==OP_Remainder
); testcase( op
==TK_REM
);
2679 assert( TK_BITAND
==OP_BitAnd
); testcase( op
==TK_BITAND
);
2680 assert( TK_BITOR
==OP_BitOr
); testcase( op
==TK_BITOR
);
2681 assert( TK_SLASH
==OP_Divide
); testcase( op
==TK_SLASH
);
2682 assert( TK_LSHIFT
==OP_ShiftLeft
); testcase( op
==TK_LSHIFT
);
2683 assert( TK_RSHIFT
==OP_ShiftRight
); testcase( op
==TK_RSHIFT
);
2684 assert( TK_CONCAT
==OP_Concat
); testcase( op
==TK_CONCAT
);
2685 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
2686 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
2687 sqlite3VdbeAddOp3(v
, op
, r2
, r1
, target
);
2688 testcase( regFree1
==0 );
2689 testcase( regFree2
==0 );
2693 Expr
*pLeft
= pExpr
->pLeft
;
2695 if( pLeft
->op
==TK_INTEGER
){
2696 codeInteger(pParse
, pLeft
, 1, target
);
2697 #ifndef SQLITE_OMIT_FLOATING_POINT
2698 }else if( pLeft
->op
==TK_FLOAT
){
2699 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2700 codeReal(v
, pLeft
->u
.zToken
, 1, target
);
2703 tempX
.op
= TK_INTEGER
;
2704 tempX
.flags
= EP_IntValue
|EP_TokenOnly
;
2706 r1
= sqlite3ExprCodeTemp(pParse
, &tempX
, ®Free1
);
2707 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free2
);
2708 sqlite3VdbeAddOp3(v
, OP_Subtract
, r2
, r1
, target
);
2709 testcase( regFree2
==0 );
2716 assert( TK_BITNOT
==OP_BitNot
); testcase( op
==TK_BITNOT
);
2717 assert( TK_NOT
==OP_Not
); testcase( op
==TK_NOT
);
2718 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
2719 testcase( regFree1
==0 );
2721 sqlite3VdbeAddOp2(v
, op
, r1
, inReg
);
2727 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
2728 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
2729 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
2730 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
2731 testcase( regFree1
==0 );
2732 addr
= sqlite3VdbeAddOp1(v
, op
, r1
);
2733 VdbeCoverageIf(v
, op
==TK_ISNULL
);
2734 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
2735 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, target
);
2736 sqlite3VdbeJumpHere(v
, addr
);
2739 case TK_AGG_FUNCTION
: {
2740 AggInfo
*pInfo
= pExpr
->pAggInfo
;
2742 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2743 sqlite3ErrorMsg(pParse
, "misuse of aggregate: %s()", pExpr
->u
.zToken
);
2745 inReg
= pInfo
->aFunc
[pExpr
->iAgg
].iMem
;
2750 ExprList
*pFarg
; /* List of function arguments */
2751 int nFarg
; /* Number of function arguments */
2752 FuncDef
*pDef
; /* The function definition object */
2753 int nId
; /* Length of the function name in bytes */
2754 const char *zId
; /* The function name */
2755 u32 constMask
= 0; /* Mask of function arguments that are constant */
2756 int i
; /* Loop counter */
2757 u8 enc
= ENC(db
); /* The text encoding used by this database */
2758 CollSeq
*pColl
= 0; /* A collating sequence */
2760 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
2761 if( ExprHasProperty(pExpr
, EP_TokenOnly
) ){
2764 pFarg
= pExpr
->x
.pList
;
2766 nFarg
= pFarg
? pFarg
->nExpr
: 0;
2767 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2768 zId
= pExpr
->u
.zToken
;
2769 nId
= sqlite3Strlen30(zId
);
2770 pDef
= sqlite3FindFunction(db
, zId
, nId
, nFarg
, enc
, 0);
2771 if( pDef
==0 || pDef
->xFunc
==0 ){
2772 sqlite3ErrorMsg(pParse
, "unknown function: %.*s()", nId
, zId
);
2776 /* Attempt a direct implementation of the built-in COALESCE() and
2777 ** IFNULL() functions. This avoids unnecessary evaluation of
2778 ** arguments past the first non-NULL argument.
2780 if( pDef
->funcFlags
& SQLITE_FUNC_COALESCE
){
2781 int endCoalesce
= sqlite3VdbeMakeLabel(v
);
2783 sqlite3ExprCode(pParse
, pFarg
->a
[0].pExpr
, target
);
2784 for(i
=1; i
<nFarg
; i
++){
2785 sqlite3VdbeAddOp2(v
, OP_NotNull
, target
, endCoalesce
);
2787 sqlite3ExprCacheRemove(pParse
, target
, 1);
2788 sqlite3ExprCachePush(pParse
);
2789 sqlite3ExprCode(pParse
, pFarg
->a
[i
].pExpr
, target
);
2790 sqlite3ExprCachePop(pParse
);
2792 sqlite3VdbeResolveLabel(v
, endCoalesce
);
2796 /* The UNLIKELY() function is a no-op. The result is the value
2797 ** of the first argument.
2799 if( pDef
->funcFlags
& SQLITE_FUNC_UNLIKELY
){
2801 sqlite3ExprCode(pParse
, pFarg
->a
[0].pExpr
, target
);
2805 for(i
=0; i
<nFarg
; i
++){
2806 if( i
<32 && sqlite3ExprIsConstant(pFarg
->a
[i
].pExpr
) ){
2808 constMask
|= MASKBIT32(i
);
2810 if( (pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
)!=0 && !pColl
){
2811 pColl
= sqlite3ExprCollSeq(pParse
, pFarg
->a
[i
].pExpr
);
2816 r1
= pParse
->nMem
+1;
2817 pParse
->nMem
+= nFarg
;
2819 r1
= sqlite3GetTempRange(pParse
, nFarg
);
2822 /* For length() and typeof() functions with a column argument,
2823 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
2824 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
2827 if( (pDef
->funcFlags
& (SQLITE_FUNC_LENGTH
|SQLITE_FUNC_TYPEOF
))!=0 ){
2830 assert( pFarg
->a
[0].pExpr
!=0 );
2831 exprOp
= pFarg
->a
[0].pExpr
->op
;
2832 if( exprOp
==TK_COLUMN
|| exprOp
==TK_AGG_COLUMN
){
2833 assert( SQLITE_FUNC_LENGTH
==OPFLAG_LENGTHARG
);
2834 assert( SQLITE_FUNC_TYPEOF
==OPFLAG_TYPEOFARG
);
2835 testcase( pDef
->funcFlags
& OPFLAG_LENGTHARG
);
2836 pFarg
->a
[0].pExpr
->op2
=
2837 pDef
->funcFlags
& (OPFLAG_LENGTHARG
|OPFLAG_TYPEOFARG
);
2841 sqlite3ExprCachePush(pParse
); /* Ticket 2ea2425d34be */
2842 sqlite3ExprCodeExprList(pParse
, pFarg
, r1
,
2843 SQLITE_ECEL_DUP
|SQLITE_ECEL_FACTOR
);
2844 sqlite3ExprCachePop(pParse
); /* Ticket 2ea2425d34be */
2848 #ifndef SQLITE_OMIT_VIRTUALTABLE
2849 /* Possibly overload the function if the first argument is
2850 ** a virtual table column.
2852 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2853 ** second argument, not the first, as the argument to test to
2854 ** see if it is a column in a virtual table. This is done because
2855 ** the left operand of infix functions (the operand we want to
2856 ** control overloading) ends up as the second argument to the
2857 ** function. The expression "A glob B" is equivalent to
2858 ** "glob(B,A). We want to use the A in "A glob B" to test
2859 ** for function overloading. But we use the B term in "glob(B,A)".
2861 if( nFarg
>=2 && (pExpr
->flags
& EP_InfixFunc
) ){
2862 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[1].pExpr
);
2863 }else if( nFarg
>0 ){
2864 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[0].pExpr
);
2867 if( pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
){
2868 if( !pColl
) pColl
= db
->pDfltColl
;
2869 sqlite3VdbeAddOp4(v
, OP_CollSeq
, 0, 0, 0, (char *)pColl
, P4_COLLSEQ
);
2871 sqlite3VdbeAddOp4(v
, OP_Function
, constMask
, r1
, target
,
2872 (char*)pDef
, P4_FUNCDEF
);
2873 sqlite3VdbeChangeP5(v
, (u8
)nFarg
);
2874 if( nFarg
&& constMask
==0 ){
2875 sqlite3ReleaseTempRange(pParse
, r1
, nFarg
);
2879 #ifndef SQLITE_OMIT_SUBQUERY
2882 testcase( op
==TK_EXISTS
);
2883 testcase( op
==TK_SELECT
);
2884 inReg
= sqlite3CodeSubselect(pParse
, pExpr
, 0, 0);
2888 int destIfFalse
= sqlite3VdbeMakeLabel(v
);
2889 int destIfNull
= sqlite3VdbeMakeLabel(v
);
2890 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
2891 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
2892 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
2893 sqlite3VdbeResolveLabel(v
, destIfFalse
);
2894 sqlite3VdbeAddOp2(v
, OP_AddImm
, target
, 0);
2895 sqlite3VdbeResolveLabel(v
, destIfNull
);
2898 #endif /* SQLITE_OMIT_SUBQUERY */
2902 ** x BETWEEN y AND z
2904 ** This is equivalent to
2908 ** X is stored in pExpr->pLeft.
2909 ** Y is stored in pExpr->pList->a[0].pExpr.
2910 ** Z is stored in pExpr->pList->a[1].pExpr.
2913 Expr
*pLeft
= pExpr
->pLeft
;
2914 struct ExprList_item
*pLItem
= pExpr
->x
.pList
->a
;
2915 Expr
*pRight
= pLItem
->pExpr
;
2917 r1
= sqlite3ExprCodeTemp(pParse
, pLeft
, ®Free1
);
2918 r2
= sqlite3ExprCodeTemp(pParse
, pRight
, ®Free2
);
2919 testcase( regFree1
==0 );
2920 testcase( regFree2
==0 );
2921 r3
= sqlite3GetTempReg(pParse
);
2922 r4
= sqlite3GetTempReg(pParse
);
2923 codeCompare(pParse
, pLeft
, pRight
, OP_Ge
,
2924 r1
, r2
, r3
, SQLITE_STOREP2
); VdbeCoverage(v
);
2926 pRight
= pLItem
->pExpr
;
2927 sqlite3ReleaseTempReg(pParse
, regFree2
);
2928 r2
= sqlite3ExprCodeTemp(pParse
, pRight
, ®Free2
);
2929 testcase( regFree2
==0 );
2930 codeCompare(pParse
, pLeft
, pRight
, OP_Le
, r1
, r2
, r4
, SQLITE_STOREP2
);
2932 sqlite3VdbeAddOp3(v
, OP_And
, r3
, r4
, target
);
2933 sqlite3ReleaseTempReg(pParse
, r3
);
2934 sqlite3ReleaseTempReg(pParse
, r4
);
2939 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
, target
);
2944 /* If the opcode is TK_TRIGGER, then the expression is a reference
2945 ** to a column in the new.* or old.* pseudo-tables available to
2946 ** trigger programs. In this case Expr.iTable is set to 1 for the
2947 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
2948 ** is set to the column of the pseudo-table to read, or to -1 to
2949 ** read the rowid field.
2951 ** The expression is implemented using an OP_Param opcode. The p1
2952 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
2953 ** to reference another column of the old.* pseudo-table, where
2954 ** i is the index of the column. For a new.rowid reference, p1 is
2955 ** set to (n+1), where n is the number of columns in each pseudo-table.
2956 ** For a reference to any other column in the new.* pseudo-table, p1
2957 ** is set to (n+2+i), where n and i are as defined previously. For
2958 ** example, if the table on which triggers are being fired is
2961 ** CREATE TABLE t1(a, b);
2963 ** Then p1 is interpreted as follows:
2965 ** p1==0 -> old.rowid p1==3 -> new.rowid
2966 ** p1==1 -> old.a p1==4 -> new.a
2967 ** p1==2 -> old.b p1==5 -> new.b
2969 Table
*pTab
= pExpr
->pTab
;
2970 int p1
= pExpr
->iTable
* (pTab
->nCol
+1) + 1 + pExpr
->iColumn
;
2972 assert( pExpr
->iTable
==0 || pExpr
->iTable
==1 );
2973 assert( pExpr
->iColumn
>=-1 && pExpr
->iColumn
<pTab
->nCol
);
2974 assert( pTab
->iPKey
<0 || pExpr
->iColumn
!=pTab
->iPKey
);
2975 assert( p1
>=0 && p1
<(pTab
->nCol
*2+2) );
2977 sqlite3VdbeAddOp2(v
, OP_Param
, p1
, target
);
2978 VdbeComment((v
, "%s.%s -> $%d",
2979 (pExpr
->iTable
? "new" : "old"),
2980 (pExpr
->iColumn
<0 ? "rowid" : pExpr
->pTab
->aCol
[pExpr
->iColumn
].zName
),
2984 #ifndef SQLITE_OMIT_FLOATING_POINT
2985 /* If the column has REAL affinity, it may currently be stored as an
2986 ** integer. Use OP_RealAffinity to make sure it is really real. */
2987 if( pExpr
->iColumn
>=0
2988 && pTab
->aCol
[pExpr
->iColumn
].affinity
==SQLITE_AFF_REAL
2990 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
2999 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3002 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3004 ** Form A is can be transformed into the equivalent form B as follows:
3005 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3006 ** WHEN x=eN THEN rN ELSE y END
3008 ** X (if it exists) is in pExpr->pLeft.
3009 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3010 ** odd. The Y is also optional. If the number of elements in x.pList
3011 ** is even, then Y is omitted and the "otherwise" result is NULL.
3012 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3014 ** The result of the expression is the Ri for the first matching Ei,
3015 ** or if there is no matching Ei, the ELSE term Y, or if there is
3016 ** no ELSE term, NULL.
3018 default: assert( op
==TK_CASE
); {
3019 int endLabel
; /* GOTO label for end of CASE stmt */
3020 int nextCase
; /* GOTO label for next WHEN clause */
3021 int nExpr
; /* 2x number of WHEN terms */
3022 int i
; /* Loop counter */
3023 ExprList
*pEList
; /* List of WHEN terms */
3024 struct ExprList_item
*aListelem
; /* Array of WHEN terms */
3025 Expr opCompare
; /* The X==Ei expression */
3026 Expr
*pX
; /* The X expression */
3027 Expr
*pTest
= 0; /* X==Ei (form A) or just Ei (form B) */
3028 VVA_ONLY( int iCacheLevel
= pParse
->iCacheLevel
; )
3030 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) && pExpr
->x
.pList
);
3031 assert(pExpr
->x
.pList
->nExpr
> 0);
3032 pEList
= pExpr
->x
.pList
;
3033 aListelem
= pEList
->a
;
3034 nExpr
= pEList
->nExpr
;
3035 endLabel
= sqlite3VdbeMakeLabel(v
);
3036 if( (pX
= pExpr
->pLeft
)!=0 ){
3038 testcase( pX
->op
==TK_COLUMN
);
3039 exprToRegister(&tempX
, sqlite3ExprCodeTemp(pParse
, pX
, ®Free1
));
3040 testcase( regFree1
==0 );
3041 opCompare
.op
= TK_EQ
;
3042 opCompare
.pLeft
= &tempX
;
3044 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3045 ** The value in regFree1 might get SCopy-ed into the file result.
3046 ** So make sure that the regFree1 register is not reused for other
3047 ** purposes and possibly overwritten. */
3050 for(i
=0; i
<nExpr
-1; i
=i
+2){
3051 sqlite3ExprCachePush(pParse
);
3054 opCompare
.pRight
= aListelem
[i
].pExpr
;
3056 pTest
= aListelem
[i
].pExpr
;
3058 nextCase
= sqlite3VdbeMakeLabel(v
);
3059 testcase( pTest
->op
==TK_COLUMN
);
3060 sqlite3ExprIfFalse(pParse
, pTest
, nextCase
, SQLITE_JUMPIFNULL
);
3061 testcase( aListelem
[i
+1].pExpr
->op
==TK_COLUMN
);
3062 sqlite3ExprCode(pParse
, aListelem
[i
+1].pExpr
, target
);
3063 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, endLabel
);
3064 sqlite3ExprCachePop(pParse
);
3065 sqlite3VdbeResolveLabel(v
, nextCase
);
3068 sqlite3ExprCachePush(pParse
);
3069 sqlite3ExprCode(pParse
, pEList
->a
[nExpr
-1].pExpr
, target
);
3070 sqlite3ExprCachePop(pParse
);
3072 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
3074 assert( db
->mallocFailed
|| pParse
->nErr
>0
3075 || pParse
->iCacheLevel
==iCacheLevel
);
3076 sqlite3VdbeResolveLabel(v
, endLabel
);
3079 #ifndef SQLITE_OMIT_TRIGGER
3081 assert( pExpr
->affinity
==OE_Rollback
3082 || pExpr
->affinity
==OE_Abort
3083 || pExpr
->affinity
==OE_Fail
3084 || pExpr
->affinity
==OE_Ignore
3086 if( !pParse
->pTriggerTab
){
3087 sqlite3ErrorMsg(pParse
,
3088 "RAISE() may only be used within a trigger-program");
3091 if( pExpr
->affinity
==OE_Abort
){
3092 sqlite3MayAbort(pParse
);
3094 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
3095 if( pExpr
->affinity
==OE_Ignore
){
3097 v
, OP_Halt
, SQLITE_OK
, OE_Ignore
, 0, pExpr
->u
.zToken
,0);
3100 sqlite3HaltConstraint(pParse
, SQLITE_CONSTRAINT_TRIGGER
,
3101 pExpr
->affinity
, pExpr
->u
.zToken
, 0, 0);
3108 sqlite3ReleaseTempReg(pParse
, regFree1
);
3109 sqlite3ReleaseTempReg(pParse
, regFree2
);
3114 ** Factor out the code of the given expression to initialization time.
3116 void sqlite3ExprCodeAtInit(
3117 Parse
*pParse
, /* Parsing context */
3118 Expr
*pExpr
, /* The expression to code when the VDBE initializes */
3119 int regDest
, /* Store the value in this register */
3120 u8 reusable
/* True if this expression is reusable */
3123 assert( ConstFactorOk(pParse
) );
3124 p
= pParse
->pConstExpr
;
3125 pExpr
= sqlite3ExprDup(pParse
->db
, pExpr
, 0);
3126 p
= sqlite3ExprListAppend(pParse
, p
, pExpr
);
3128 struct ExprList_item
*pItem
= &p
->a
[p
->nExpr
-1];
3129 pItem
->u
.iConstExprReg
= regDest
;
3130 pItem
->reusable
= reusable
;
3132 pParse
->pConstExpr
= p
;
3136 ** Generate code to evaluate an expression and store the results
3137 ** into a register. Return the register number where the results
3140 ** If the register is a temporary register that can be deallocated,
3141 ** then write its number into *pReg. If the result register is not
3142 ** a temporary, then set *pReg to zero.
3144 ** If pExpr is a constant, then this routine might generate this
3145 ** code to fill the register in the initialization section of the
3146 ** VDBE program, in order to factor it out of the evaluation loop.
3148 int sqlite3ExprCodeTemp(Parse
*pParse
, Expr
*pExpr
, int *pReg
){
3150 pExpr
= sqlite3ExprSkipCollate(pExpr
);
3151 if( ConstFactorOk(pParse
)
3152 && pExpr
->op
!=TK_REGISTER
3153 && sqlite3ExprIsConstantNotJoin(pExpr
)
3155 ExprList
*p
= pParse
->pConstExpr
;
3159 struct ExprList_item
*pItem
;
3160 for(pItem
=p
->a
, i
=p
->nExpr
; i
>0; pItem
++, i
--){
3161 if( pItem
->reusable
&& sqlite3ExprCompare(pItem
->pExpr
,pExpr
,-1)==0 ){
3162 return pItem
->u
.iConstExprReg
;
3166 r2
= ++pParse
->nMem
;
3167 sqlite3ExprCodeAtInit(pParse
, pExpr
, r2
, 1);
3169 int r1
= sqlite3GetTempReg(pParse
);
3170 r2
= sqlite3ExprCodeTarget(pParse
, pExpr
, r1
);
3174 sqlite3ReleaseTempReg(pParse
, r1
);
3182 ** Generate code that will evaluate expression pExpr and store the
3183 ** results in register target. The results are guaranteed to appear
3184 ** in register target.
3186 void sqlite3ExprCode(Parse
*pParse
, Expr
*pExpr
, int target
){
3189 assert( target
>0 && target
<=pParse
->nMem
);
3190 if( pExpr
&& pExpr
->op
==TK_REGISTER
){
3191 sqlite3VdbeAddOp2(pParse
->pVdbe
, OP_Copy
, pExpr
->iTable
, target
);
3193 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
);
3194 assert( pParse
->pVdbe
|| pParse
->db
->mallocFailed
);
3195 if( inReg
!=target
&& pParse
->pVdbe
){
3196 sqlite3VdbeAddOp2(pParse
->pVdbe
, OP_SCopy
, inReg
, target
);
3202 ** Generate code that will evaluate expression pExpr and store the
3203 ** results in register target. The results are guaranteed to appear
3204 ** in register target. If the expression is constant, then this routine
3205 ** might choose to code the expression at initialization time.
3207 void sqlite3ExprCodeFactorable(Parse
*pParse
, Expr
*pExpr
, int target
){
3208 if( pParse
->okConstFactor
&& sqlite3ExprIsConstant(pExpr
) ){
3209 sqlite3ExprCodeAtInit(pParse
, pExpr
, target
, 0);
3211 sqlite3ExprCode(pParse
, pExpr
, target
);
3216 ** Generate code that evaluates the given expression and puts the result
3217 ** in register target.
3219 ** Also make a copy of the expression results into another "cache" register
3220 ** and modify the expression so that the next time it is evaluated,
3221 ** the result is a copy of the cache register.
3223 ** This routine is used for expressions that are used multiple
3224 ** times. They are evaluated once and the results of the expression
3227 void sqlite3ExprCodeAndCache(Parse
*pParse
, Expr
*pExpr
, int target
){
3228 Vdbe
*v
= pParse
->pVdbe
;
3232 assert( pExpr
->op
!=TK_REGISTER
);
3233 sqlite3ExprCode(pParse
, pExpr
, target
);
3234 iMem
= ++pParse
->nMem
;
3235 sqlite3VdbeAddOp2(v
, OP_Copy
, target
, iMem
);
3236 exprToRegister(pExpr
, iMem
);
3241 ** Generate a human-readable explanation of an expression tree.
3243 void sqlite3TreeViewExpr(TreeView
*pView
, const Expr
*pExpr
, u8 moreToFollow
){
3244 const char *zBinOp
= 0; /* Binary operator */
3245 const char *zUniOp
= 0; /* Unary operator */
3246 pView
= sqlite3TreeViewPush(pView
, moreToFollow
);
3248 sqlite3TreeViewLine(pView
, "nil");
3249 sqlite3TreeViewPop(pView
);
3252 switch( pExpr
->op
){
3253 case TK_AGG_COLUMN
: {
3254 sqlite3TreeViewLine(pView
, "AGG{%d:%d}",
3255 pExpr
->iTable
, pExpr
->iColumn
);
3259 if( pExpr
->iTable
<0 ){
3260 /* This only happens when coding check constraints */
3261 sqlite3TreeViewLine(pView
, "COLUMN(%d)", pExpr
->iColumn
);
3263 sqlite3TreeViewLine(pView
, "{%d:%d}",
3264 pExpr
->iTable
, pExpr
->iColumn
);
3269 if( pExpr
->flags
& EP_IntValue
){
3270 sqlite3TreeViewLine(pView
, "%d", pExpr
->u
.iValue
);
3272 sqlite3TreeViewLine(pView
, "%s", pExpr
->u
.zToken
);
3276 #ifndef SQLITE_OMIT_FLOATING_POINT
3278 sqlite3TreeViewLine(pView
,"%s", pExpr
->u
.zToken
);
3283 sqlite3TreeViewLine(pView
,"%Q", pExpr
->u
.zToken
);
3287 sqlite3TreeViewLine(pView
,"NULL");
3290 #ifndef SQLITE_OMIT_BLOB_LITERAL
3292 sqlite3TreeViewLine(pView
,"%s", pExpr
->u
.zToken
);
3297 sqlite3TreeViewLine(pView
,"VARIABLE(%s,%d)",
3298 pExpr
->u
.zToken
, pExpr
->iColumn
);
3302 sqlite3TreeViewLine(pView
,"REGISTER(%d)", pExpr
->iTable
);
3306 sqlite3TreeViewLine(pView
,"AS %Q", pExpr
->u
.zToken
);
3307 sqlite3TreeViewExpr(pView
, pExpr
->pLeft
, 0);
3311 sqlite3TreeViewLine(pView
,"ID %Q", pExpr
->u
.zToken
);
3314 #ifndef SQLITE_OMIT_CAST
3316 /* Expressions of the form: CAST(pLeft AS token) */
3317 sqlite3TreeViewLine(pView
,"CAST %Q", pExpr
->u
.zToken
);
3318 sqlite3TreeViewExpr(pView
, pExpr
->pLeft
, 0);
3321 #endif /* SQLITE_OMIT_CAST */
3322 case TK_LT
: zBinOp
= "LT"; break;
3323 case TK_LE
: zBinOp
= "LE"; break;
3324 case TK_GT
: zBinOp
= "GT"; break;
3325 case TK_GE
: zBinOp
= "GE"; break;
3326 case TK_NE
: zBinOp
= "NE"; break;
3327 case TK_EQ
: zBinOp
= "EQ"; break;
3328 case TK_IS
: zBinOp
= "IS"; break;
3329 case TK_ISNOT
: zBinOp
= "ISNOT"; break;
3330 case TK_AND
: zBinOp
= "AND"; break;
3331 case TK_OR
: zBinOp
= "OR"; break;
3332 case TK_PLUS
: zBinOp
= "ADD"; break;
3333 case TK_STAR
: zBinOp
= "MUL"; break;
3334 case TK_MINUS
: zBinOp
= "SUB"; break;
3335 case TK_REM
: zBinOp
= "REM"; break;
3336 case TK_BITAND
: zBinOp
= "BITAND"; break;
3337 case TK_BITOR
: zBinOp
= "BITOR"; break;
3338 case TK_SLASH
: zBinOp
= "DIV"; break;
3339 case TK_LSHIFT
: zBinOp
= "LSHIFT"; break;
3340 case TK_RSHIFT
: zBinOp
= "RSHIFT"; break;
3341 case TK_CONCAT
: zBinOp
= "CONCAT"; break;
3342 case TK_DOT
: zBinOp
= "DOT"; break;
3344 case TK_UMINUS
: zUniOp
= "UMINUS"; break;
3345 case TK_UPLUS
: zUniOp
= "UPLUS"; break;
3346 case TK_BITNOT
: zUniOp
= "BITNOT"; break;
3347 case TK_NOT
: zUniOp
= "NOT"; break;
3348 case TK_ISNULL
: zUniOp
= "ISNULL"; break;
3349 case TK_NOTNULL
: zUniOp
= "NOTNULL"; break;
3352 sqlite3TreeViewLine(pView
, "COLLATE %Q", pExpr
->u
.zToken
);
3353 sqlite3TreeViewExpr(pView
, pExpr
->pLeft
, 0);
3357 case TK_AGG_FUNCTION
:
3359 ExprList
*pFarg
; /* List of function arguments */
3360 if( ExprHasProperty(pExpr
, EP_TokenOnly
) ){
3363 pFarg
= pExpr
->x
.pList
;
3365 if( pExpr
->op
==TK_AGG_FUNCTION
){
3366 sqlite3TreeViewLine(pView
, "AGG_FUNCTION%d %Q",
3367 pExpr
->op2
, pExpr
->u
.zToken
);
3369 sqlite3TreeViewLine(pView
, "FUNCTION %Q", pExpr
->u
.zToken
);
3372 sqlite3TreeViewExprList(pView
, pFarg
, 0, 0);
3376 #ifndef SQLITE_OMIT_SUBQUERY
3378 sqlite3TreeViewLine(pView
, "EXISTS-expr");
3379 sqlite3TreeViewSelect(pView
, pExpr
->x
.pSelect
, 0);
3383 sqlite3TreeViewLine(pView
, "SELECT-expr");
3384 sqlite3TreeViewSelect(pView
, pExpr
->x
.pSelect
, 0);
3388 sqlite3TreeViewLine(pView
, "IN");
3389 sqlite3TreeViewExpr(pView
, pExpr
->pLeft
, 1);
3390 if( ExprHasProperty(pExpr
, EP_xIsSelect
) ){
3391 sqlite3TreeViewSelect(pView
, pExpr
->x
.pSelect
, 0);
3393 sqlite3TreeViewExprList(pView
, pExpr
->x
.pList
, 0, 0);
3397 #endif /* SQLITE_OMIT_SUBQUERY */
3400 ** x BETWEEN y AND z
3402 ** This is equivalent to
3406 ** X is stored in pExpr->pLeft.
3407 ** Y is stored in pExpr->pList->a[0].pExpr.
3408 ** Z is stored in pExpr->pList->a[1].pExpr.
3411 Expr
*pX
= pExpr
->pLeft
;
3412 Expr
*pY
= pExpr
->x
.pList
->a
[0].pExpr
;
3413 Expr
*pZ
= pExpr
->x
.pList
->a
[1].pExpr
;
3414 sqlite3TreeViewLine(pView
, "BETWEEN");
3415 sqlite3TreeViewExpr(pView
, pX
, 1);
3416 sqlite3TreeViewExpr(pView
, pY
, 1);
3417 sqlite3TreeViewExpr(pView
, pZ
, 0);
3421 /* If the opcode is TK_TRIGGER, then the expression is a reference
3422 ** to a column in the new.* or old.* pseudo-tables available to
3423 ** trigger programs. In this case Expr.iTable is set to 1 for the
3424 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3425 ** is set to the column of the pseudo-table to read, or to -1 to
3426 ** read the rowid field.
3428 sqlite3TreeViewLine(pView
, "%s(%d)",
3429 pExpr
->iTable
? "NEW" : "OLD", pExpr
->iColumn
);
3433 sqlite3TreeViewLine(pView
, "CASE");
3434 sqlite3TreeViewExpr(pView
, pExpr
->pLeft
, 1);
3435 sqlite3TreeViewExprList(pView
, pExpr
->x
.pList
, 0, 0);
3438 #ifndef SQLITE_OMIT_TRIGGER
3440 const char *zType
= "unk";
3441 switch( pExpr
->affinity
){
3442 case OE_Rollback
: zType
= "rollback"; break;
3443 case OE_Abort
: zType
= "abort"; break;
3444 case OE_Fail
: zType
= "fail"; break;
3445 case OE_Ignore
: zType
= "ignore"; break;
3447 sqlite3TreeViewLine(pView
, "RAISE %s(%Q)", zType
, pExpr
->u
.zToken
);
3452 sqlite3TreeViewLine(pView
, "op=%d", pExpr
->op
);
3457 sqlite3TreeViewLine(pView
, "%s", zBinOp
);
3458 sqlite3TreeViewExpr(pView
, pExpr
->pLeft
, 1);
3459 sqlite3TreeViewExpr(pView
, pExpr
->pRight
, 0);
3461 sqlite3TreeViewLine(pView
, "%s", zUniOp
);
3462 sqlite3TreeViewExpr(pView
, pExpr
->pLeft
, 0);
3464 sqlite3TreeViewPop(pView
);
3466 #endif /* SQLITE_DEBUG */
3470 ** Generate a human-readable explanation of an expression list.
3472 void sqlite3TreeViewExprList(
3474 const ExprList
*pList
,
3479 pView
= sqlite3TreeViewPush(pView
, moreToFollow
);
3480 if( zLabel
==0 || zLabel
[0]==0 ) zLabel
= "LIST";
3482 sqlite3TreeViewLine(pView
, "%s (empty)", zLabel
);
3484 sqlite3TreeViewLine(pView
, "%s", zLabel
);
3485 for(i
=0; i
<pList
->nExpr
; i
++){
3486 sqlite3TreeViewExpr(pView
, pList
->a
[i
].pExpr
, i
<pList
->nExpr
-1);
3488 if( pList
->a
[i
].zName
){
3489 sqlite3ExplainPrintf(pOut
, " AS %s", pList
->a
[i
].zName
);
3491 if( pList
->a
[i
].bSpanIsTab
){
3492 sqlite3ExplainPrintf(pOut
, " (%s)", pList
->a
[i
].zSpan
);
3497 sqlite3TreeViewPop(pView
);
3499 #endif /* SQLITE_DEBUG */
3502 ** Generate code that pushes the value of every element of the given
3503 ** expression list into a sequence of registers beginning at target.
3505 ** Return the number of elements evaluated.
3507 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
3508 ** filled using OP_SCopy. OP_Copy must be used instead.
3510 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
3511 ** factored out into initialization code.
3513 int sqlite3ExprCodeExprList(
3514 Parse
*pParse
, /* Parsing context */
3515 ExprList
*pList
, /* The expression list to be coded */
3516 int target
, /* Where to write results */
3517 u8 flags
/* SQLITE_ECEL_* flags */
3519 struct ExprList_item
*pItem
;
3521 u8 copyOp
= (flags
& SQLITE_ECEL_DUP
) ? OP_Copy
: OP_SCopy
;
3524 assert( pParse
->pVdbe
!=0 ); /* Never gets this far otherwise */
3526 if( !ConstFactorOk(pParse
) ) flags
&= ~SQLITE_ECEL_FACTOR
;
3527 for(pItem
=pList
->a
, i
=0; i
<n
; i
++, pItem
++){
3528 Expr
*pExpr
= pItem
->pExpr
;
3529 if( (flags
& SQLITE_ECEL_FACTOR
)!=0 && sqlite3ExprIsConstant(pExpr
) ){
3530 sqlite3ExprCodeAtInit(pParse
, pExpr
, target
+i
, 0);
3532 int inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
+i
);
3533 if( inReg
!=target
+i
){
3535 Vdbe
*v
= pParse
->pVdbe
;
3537 && (pOp
=sqlite3VdbeGetOp(v
, -1))->opcode
==OP_Copy
3538 && pOp
->p1
+pOp
->p3
+1==inReg
3539 && pOp
->p2
+pOp
->p3
+1==target
+i
3543 sqlite3VdbeAddOp2(v
, copyOp
, inReg
, target
+i
);
3552 ** Generate code for a BETWEEN operator.
3554 ** x BETWEEN y AND z
3556 ** The above is equivalent to
3560 ** Code it as such, taking care to do the common subexpression
3561 ** elimination of x.
3563 static void exprCodeBetween(
3564 Parse
*pParse
, /* Parsing and code generating context */
3565 Expr
*pExpr
, /* The BETWEEN expression */
3566 int dest
, /* Jump here if the jump is taken */
3567 int jumpIfTrue
, /* Take the jump if the BETWEEN is true */
3568 int jumpIfNull
/* Take the jump if the BETWEEN is NULL */
3570 Expr exprAnd
; /* The AND operator in x>=y AND x<=z */
3571 Expr compLeft
; /* The x>=y term */
3572 Expr compRight
; /* The x<=z term */
3573 Expr exprX
; /* The x subexpression */
3574 int regFree1
= 0; /* Temporary use register */
3576 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
3577 exprX
= *pExpr
->pLeft
;
3578 exprAnd
.op
= TK_AND
;
3579 exprAnd
.pLeft
= &compLeft
;
3580 exprAnd
.pRight
= &compRight
;
3581 compLeft
.op
= TK_GE
;
3582 compLeft
.pLeft
= &exprX
;
3583 compLeft
.pRight
= pExpr
->x
.pList
->a
[0].pExpr
;
3584 compRight
.op
= TK_LE
;
3585 compRight
.pLeft
= &exprX
;
3586 compRight
.pRight
= pExpr
->x
.pList
->a
[1].pExpr
;
3587 exprToRegister(&exprX
, sqlite3ExprCodeTemp(pParse
, &exprX
, ®Free1
));
3589 sqlite3ExprIfTrue(pParse
, &exprAnd
, dest
, jumpIfNull
);
3591 sqlite3ExprIfFalse(pParse
, &exprAnd
, dest
, jumpIfNull
);
3593 sqlite3ReleaseTempReg(pParse
, regFree1
);
3595 /* Ensure adequate test coverage */
3596 testcase( jumpIfTrue
==0 && jumpIfNull
==0 && regFree1
==0 );
3597 testcase( jumpIfTrue
==0 && jumpIfNull
==0 && regFree1
!=0 );
3598 testcase( jumpIfTrue
==0 && jumpIfNull
!=0 && regFree1
==0 );
3599 testcase( jumpIfTrue
==0 && jumpIfNull
!=0 && regFree1
!=0 );
3600 testcase( jumpIfTrue
!=0 && jumpIfNull
==0 && regFree1
==0 );
3601 testcase( jumpIfTrue
!=0 && jumpIfNull
==0 && regFree1
!=0 );
3602 testcase( jumpIfTrue
!=0 && jumpIfNull
!=0 && regFree1
==0 );
3603 testcase( jumpIfTrue
!=0 && jumpIfNull
!=0 && regFree1
!=0 );
3607 ** Generate code for a boolean expression such that a jump is made
3608 ** to the label "dest" if the expression is true but execution
3609 ** continues straight thru if the expression is false.
3611 ** If the expression evaluates to NULL (neither true nor false), then
3612 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
3614 ** This code depends on the fact that certain token values (ex: TK_EQ)
3615 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3616 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
3617 ** the make process cause these values to align. Assert()s in the code
3618 ** below verify that the numbers are aligned correctly.
3620 void sqlite3ExprIfTrue(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
3621 Vdbe
*v
= pParse
->pVdbe
;
3627 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
3628 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
3629 if( NEVER(pExpr
==0) ) return; /* No way this can happen */
3633 int d2
= sqlite3VdbeMakeLabel(v
);
3634 testcase( jumpIfNull
==0 );
3635 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, d2
,jumpIfNull
^SQLITE_JUMPIFNULL
);
3636 sqlite3ExprCachePush(pParse
);
3637 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
3638 sqlite3VdbeResolveLabel(v
, d2
);
3639 sqlite3ExprCachePop(pParse
);
3643 testcase( jumpIfNull
==0 );
3644 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
3645 sqlite3ExprCachePush(pParse
);
3646 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
3647 sqlite3ExprCachePop(pParse
);
3651 testcase( jumpIfNull
==0 );
3652 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
3661 testcase( jumpIfNull
==0 );
3662 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
3663 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
3664 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
3665 r1
, r2
, dest
, jumpIfNull
);
3666 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
3667 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
3668 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
3669 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
3670 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
3671 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
3672 testcase( regFree1
==0 );
3673 testcase( regFree2
==0 );
3678 testcase( op
==TK_IS
);
3679 testcase( op
==TK_ISNOT
);
3680 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
3681 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
3682 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
3683 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
3684 r1
, r2
, dest
, SQLITE_NULLEQ
);
3685 VdbeCoverageIf(v
, op
==TK_EQ
);
3686 VdbeCoverageIf(v
, op
==TK_NE
);
3687 testcase( regFree1
==0 );
3688 testcase( regFree2
==0 );
3693 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
3694 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
3695 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
3696 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
3697 VdbeCoverageIf(v
, op
==TK_ISNULL
);
3698 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
3699 testcase( regFree1
==0 );
3703 testcase( jumpIfNull
==0 );
3704 exprCodeBetween(pParse
, pExpr
, dest
, 1, jumpIfNull
);
3707 #ifndef SQLITE_OMIT_SUBQUERY
3709 int destIfFalse
= sqlite3VdbeMakeLabel(v
);
3710 int destIfNull
= jumpIfNull
? dest
: destIfFalse
;
3711 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
3712 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, dest
);
3713 sqlite3VdbeResolveLabel(v
, destIfFalse
);
3718 if( exprAlwaysTrue(pExpr
) ){
3719 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, dest
);
3720 }else if( exprAlwaysFalse(pExpr
) ){
3723 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
3724 sqlite3VdbeAddOp3(v
, OP_If
, r1
, dest
, jumpIfNull
!=0);
3726 testcase( regFree1
==0 );
3727 testcase( jumpIfNull
==0 );
3732 sqlite3ReleaseTempReg(pParse
, regFree1
);
3733 sqlite3ReleaseTempReg(pParse
, regFree2
);
3737 ** Generate code for a boolean expression such that a jump is made
3738 ** to the label "dest" if the expression is false but execution
3739 ** continues straight thru if the expression is true.
3741 ** If the expression evaluates to NULL (neither true nor false) then
3742 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
3745 void sqlite3ExprIfFalse(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
3746 Vdbe
*v
= pParse
->pVdbe
;
3752 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
3753 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
3754 if( pExpr
==0 ) return;
3756 /* The value of pExpr->op and op are related as follows:
3759 ** --------- ----------
3760 ** TK_ISNULL OP_NotNull
3761 ** TK_NOTNULL OP_IsNull
3769 ** For other values of pExpr->op, op is undefined and unused.
3770 ** The value of TK_ and OP_ constants are arranged such that we
3771 ** can compute the mapping above using the following expression.
3772 ** Assert()s verify that the computation is correct.
3774 op
= ((pExpr
->op
+(TK_ISNULL
&1))^1)-(TK_ISNULL
&1);
3776 /* Verify correct alignment of TK_ and OP_ constants
3778 assert( pExpr
->op
!=TK_ISNULL
|| op
==OP_NotNull
);
3779 assert( pExpr
->op
!=TK_NOTNULL
|| op
==OP_IsNull
);
3780 assert( pExpr
->op
!=TK_NE
|| op
==OP_Eq
);
3781 assert( pExpr
->op
!=TK_EQ
|| op
==OP_Ne
);
3782 assert( pExpr
->op
!=TK_LT
|| op
==OP_Ge
);
3783 assert( pExpr
->op
!=TK_LE
|| op
==OP_Gt
);
3784 assert( pExpr
->op
!=TK_GT
|| op
==OP_Le
);
3785 assert( pExpr
->op
!=TK_GE
|| op
==OP_Lt
);
3787 switch( pExpr
->op
){
3789 testcase( jumpIfNull
==0 );
3790 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
3791 sqlite3ExprCachePush(pParse
);
3792 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
3793 sqlite3ExprCachePop(pParse
);
3797 int d2
= sqlite3VdbeMakeLabel(v
);
3798 testcase( jumpIfNull
==0 );
3799 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, d2
, jumpIfNull
^SQLITE_JUMPIFNULL
);
3800 sqlite3ExprCachePush(pParse
);
3801 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
3802 sqlite3VdbeResolveLabel(v
, d2
);
3803 sqlite3ExprCachePop(pParse
);
3807 testcase( jumpIfNull
==0 );
3808 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
3817 testcase( jumpIfNull
==0 );
3818 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
3819 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
3820 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
3821 r1
, r2
, dest
, jumpIfNull
);
3822 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
3823 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
3824 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
3825 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
3826 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
3827 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
3828 testcase( regFree1
==0 );
3829 testcase( regFree2
==0 );
3834 testcase( pExpr
->op
==TK_IS
);
3835 testcase( pExpr
->op
==TK_ISNOT
);
3836 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
3837 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
3838 op
= (pExpr
->op
==TK_IS
) ? TK_NE
: TK_EQ
;
3839 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
3840 r1
, r2
, dest
, SQLITE_NULLEQ
);
3841 VdbeCoverageIf(v
, op
==TK_EQ
);
3842 VdbeCoverageIf(v
, op
==TK_NE
);
3843 testcase( regFree1
==0 );
3844 testcase( regFree2
==0 );
3849 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
3850 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
3851 testcase( op
==TK_ISNULL
); VdbeCoverageIf(v
, op
==TK_ISNULL
);
3852 testcase( op
==TK_NOTNULL
); VdbeCoverageIf(v
, op
==TK_NOTNULL
);
3853 testcase( regFree1
==0 );
3857 testcase( jumpIfNull
==0 );
3858 exprCodeBetween(pParse
, pExpr
, dest
, 0, jumpIfNull
);
3861 #ifndef SQLITE_OMIT_SUBQUERY
3864 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, dest
);
3866 int destIfNull
= sqlite3VdbeMakeLabel(v
);
3867 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, destIfNull
);
3868 sqlite3VdbeResolveLabel(v
, destIfNull
);
3874 if( exprAlwaysFalse(pExpr
) ){
3875 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, dest
);
3876 }else if( exprAlwaysTrue(pExpr
) ){
3879 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
3880 sqlite3VdbeAddOp3(v
, OP_IfNot
, r1
, dest
, jumpIfNull
!=0);
3882 testcase( regFree1
==0 );
3883 testcase( jumpIfNull
==0 );
3888 sqlite3ReleaseTempReg(pParse
, regFree1
);
3889 sqlite3ReleaseTempReg(pParse
, regFree2
);
3893 ** Do a deep comparison of two expression trees. Return 0 if the two
3894 ** expressions are completely identical. Return 1 if they differ only
3895 ** by a COLLATE operator at the top level. Return 2 if there are differences
3896 ** other than the top-level COLLATE operator.
3898 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
3899 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
3901 ** The pA side might be using TK_REGISTER. If that is the case and pB is
3902 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
3904 ** Sometimes this routine will return 2 even if the two expressions
3905 ** really are equivalent. If we cannot prove that the expressions are
3906 ** identical, we return 2 just to be safe. So if this routine
3907 ** returns 2, then you do not really know for certain if the two
3908 ** expressions are the same. But if you get a 0 or 1 return, then you
3909 ** can be sure the expressions are the same. In the places where
3910 ** this routine is used, it does not hurt to get an extra 2 - that
3911 ** just might result in some slightly slower code. But returning
3912 ** an incorrect 0 or 1 could lead to a malfunction.
3914 int sqlite3ExprCompare(Expr
*pA
, Expr
*pB
, int iTab
){
3916 if( pA
==0 || pB
==0 ){
3917 return pB
==pA
? 0 : 2;
3919 combinedFlags
= pA
->flags
| pB
->flags
;
3920 if( combinedFlags
& EP_IntValue
){
3921 if( (pA
->flags
&pB
->flags
&EP_IntValue
)!=0 && pA
->u
.iValue
==pB
->u
.iValue
){
3926 if( pA
->op
!=pB
->op
){
3927 if( pA
->op
==TK_COLLATE
&& sqlite3ExprCompare(pA
->pLeft
, pB
, iTab
)<2 ){
3930 if( pB
->op
==TK_COLLATE
&& sqlite3ExprCompare(pA
, pB
->pLeft
, iTab
)<2 ){
3935 if( pA
->op
!=TK_COLUMN
&& ALWAYS(pA
->op
!=TK_AGG_COLUMN
) && pA
->u
.zToken
){
3936 if( strcmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ){
3937 return pA
->op
==TK_COLLATE
? 1 : 2;
3940 if( (pA
->flags
& EP_Distinct
)!=(pB
->flags
& EP_Distinct
) ) return 2;
3941 if( ALWAYS((combinedFlags
& EP_TokenOnly
)==0) ){
3942 if( combinedFlags
& EP_xIsSelect
) return 2;
3943 if( sqlite3ExprCompare(pA
->pLeft
, pB
->pLeft
, iTab
) ) return 2;
3944 if( sqlite3ExprCompare(pA
->pRight
, pB
->pRight
, iTab
) ) return 2;
3945 if( sqlite3ExprListCompare(pA
->x
.pList
, pB
->x
.pList
, iTab
) ) return 2;
3946 if( ALWAYS((combinedFlags
& EP_Reduced
)==0) ){
3947 if( pA
->iColumn
!=pB
->iColumn
) return 2;
3948 if( pA
->iTable
!=pB
->iTable
3949 && (pA
->iTable
!=iTab
|| NEVER(pB
->iTable
>=0)) ) return 2;
3956 ** Compare two ExprList objects. Return 0 if they are identical and
3957 ** non-zero if they differ in any way.
3959 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
3960 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
3962 ** This routine might return non-zero for equivalent ExprLists. The
3963 ** only consequence will be disabled optimizations. But this routine
3964 ** must never return 0 if the two ExprList objects are different, or
3965 ** a malfunction will result.
3967 ** Two NULL pointers are considered to be the same. But a NULL pointer
3968 ** always differs from a non-NULL pointer.
3970 int sqlite3ExprListCompare(ExprList
*pA
, ExprList
*pB
, int iTab
){
3972 if( pA
==0 && pB
==0 ) return 0;
3973 if( pA
==0 || pB
==0 ) return 1;
3974 if( pA
->nExpr
!=pB
->nExpr
) return 1;
3975 for(i
=0; i
<pA
->nExpr
; i
++){
3976 Expr
*pExprA
= pA
->a
[i
].pExpr
;
3977 Expr
*pExprB
= pB
->a
[i
].pExpr
;
3978 if( pA
->a
[i
].sortOrder
!=pB
->a
[i
].sortOrder
) return 1;
3979 if( sqlite3ExprCompare(pExprA
, pExprB
, iTab
) ) return 1;
3985 ** Return true if we can prove the pE2 will always be true if pE1 is
3986 ** true. Return false if we cannot complete the proof or if pE2 might
3987 ** be false. Examples:
3989 ** pE1: x==5 pE2: x==5 Result: true
3990 ** pE1: x>0 pE2: x==5 Result: false
3991 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
3992 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
3993 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
3994 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
3995 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
3997 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
3998 ** Expr.iTable<0 then assume a table number given by iTab.
4000 ** When in doubt, return false. Returning true might give a performance
4001 ** improvement. Returning false might cause a performance reduction, but
4002 ** it will always give the correct answer and is hence always safe.
4004 int sqlite3ExprImpliesExpr(Expr
*pE1
, Expr
*pE2
, int iTab
){
4005 if( sqlite3ExprCompare(pE1
, pE2
, iTab
)==0 ){
4009 && (sqlite3ExprImpliesExpr(pE1
, pE2
->pLeft
, iTab
)
4010 || sqlite3ExprImpliesExpr(pE1
, pE2
->pRight
, iTab
) )
4014 if( pE2
->op
==TK_NOTNULL
4015 && sqlite3ExprCompare(pE1
->pLeft
, pE2
->pLeft
, iTab
)==0
4016 && (pE1
->op
!=TK_ISNULL
&& pE1
->op
!=TK_IS
)
4024 ** An instance of the following structure is used by the tree walker
4025 ** to count references to table columns in the arguments of an
4026 ** aggregate function, in order to implement the
4027 ** sqlite3FunctionThisSrc() routine.
4030 SrcList
*pSrc
; /* One particular FROM clause in a nested query */
4031 int nThis
; /* Number of references to columns in pSrcList */
4032 int nOther
; /* Number of references to columns in other FROM clauses */
4036 ** Count the number of references to columns.
4038 static int exprSrcCount(Walker
*pWalker
, Expr
*pExpr
){
4039 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4040 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4041 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
4042 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4043 ** NEVER() will need to be removed. */
4044 if( pExpr
->op
==TK_COLUMN
|| NEVER(pExpr
->op
==TK_AGG_COLUMN
) ){
4046 struct SrcCount
*p
= pWalker
->u
.pSrcCount
;
4047 SrcList
*pSrc
= p
->pSrc
;
4048 for(i
=0; i
<pSrc
->nSrc
; i
++){
4049 if( pExpr
->iTable
==pSrc
->a
[i
].iCursor
) break;
4057 return WRC_Continue
;
4061 ** Determine if any of the arguments to the pExpr Function reference
4062 ** pSrcList. Return true if they do. Also return true if the function
4063 ** has no arguments or has only constant arguments. Return false if pExpr
4064 ** references columns but not columns of tables found in pSrcList.
4066 int sqlite3FunctionUsesThisSrc(Expr
*pExpr
, SrcList
*pSrcList
){
4068 struct SrcCount cnt
;
4069 assert( pExpr
->op
==TK_AGG_FUNCTION
);
4070 memset(&w
, 0, sizeof(w
));
4071 w
.xExprCallback
= exprSrcCount
;
4072 w
.u
.pSrcCount
= &cnt
;
4073 cnt
.pSrc
= pSrcList
;
4076 sqlite3WalkExprList(&w
, pExpr
->x
.pList
);
4077 return cnt
.nThis
>0 || cnt
.nOther
==0;
4081 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
4082 ** the new element. Return a negative number if malloc fails.
4084 static int addAggInfoColumn(sqlite3
*db
, AggInfo
*pInfo
){
4086 pInfo
->aCol
= sqlite3ArrayAllocate(
4089 sizeof(pInfo
->aCol
[0]),
4097 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4098 ** the new element. Return a negative number if malloc fails.
4100 static int addAggInfoFunc(sqlite3
*db
, AggInfo
*pInfo
){
4102 pInfo
->aFunc
= sqlite3ArrayAllocate(
4105 sizeof(pInfo
->aFunc
[0]),
4113 ** This is the xExprCallback for a tree walker. It is used to
4114 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
4115 ** for additional information.
4117 static int analyzeAggregate(Walker
*pWalker
, Expr
*pExpr
){
4119 NameContext
*pNC
= pWalker
->u
.pNC
;
4120 Parse
*pParse
= pNC
->pParse
;
4121 SrcList
*pSrcList
= pNC
->pSrcList
;
4122 AggInfo
*pAggInfo
= pNC
->pAggInfo
;
4124 switch( pExpr
->op
){
4127 testcase( pExpr
->op
==TK_AGG_COLUMN
);
4128 testcase( pExpr
->op
==TK_COLUMN
);
4129 /* Check to see if the column is in one of the tables in the FROM
4130 ** clause of the aggregate query */
4131 if( ALWAYS(pSrcList
!=0) ){
4132 struct SrcList_item
*pItem
= pSrcList
->a
;
4133 for(i
=0; i
<pSrcList
->nSrc
; i
++, pItem
++){
4134 struct AggInfo_col
*pCol
;
4135 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
4136 if( pExpr
->iTable
==pItem
->iCursor
){
4137 /* If we reach this point, it means that pExpr refers to a table
4138 ** that is in the FROM clause of the aggregate query.
4140 ** Make an entry for the column in pAggInfo->aCol[] if there
4141 ** is not an entry there already.
4144 pCol
= pAggInfo
->aCol
;
4145 for(k
=0; k
<pAggInfo
->nColumn
; k
++, pCol
++){
4146 if( pCol
->iTable
==pExpr
->iTable
&&
4147 pCol
->iColumn
==pExpr
->iColumn
){
4151 if( (k
>=pAggInfo
->nColumn
)
4152 && (k
= addAggInfoColumn(pParse
->db
, pAggInfo
))>=0
4154 pCol
= &pAggInfo
->aCol
[k
];
4155 pCol
->pTab
= pExpr
->pTab
;
4156 pCol
->iTable
= pExpr
->iTable
;
4157 pCol
->iColumn
= pExpr
->iColumn
;
4158 pCol
->iMem
= ++pParse
->nMem
;
4159 pCol
->iSorterColumn
= -1;
4160 pCol
->pExpr
= pExpr
;
4161 if( pAggInfo
->pGroupBy
){
4163 ExprList
*pGB
= pAggInfo
->pGroupBy
;
4164 struct ExprList_item
*pTerm
= pGB
->a
;
4166 for(j
=0; j
<n
; j
++, pTerm
++){
4167 Expr
*pE
= pTerm
->pExpr
;
4168 if( pE
->op
==TK_COLUMN
&& pE
->iTable
==pExpr
->iTable
&&
4169 pE
->iColumn
==pExpr
->iColumn
){
4170 pCol
->iSorterColumn
= j
;
4175 if( pCol
->iSorterColumn
<0 ){
4176 pCol
->iSorterColumn
= pAggInfo
->nSortingColumn
++;
4179 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4180 ** because it was there before or because we just created it).
4181 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4182 ** pAggInfo->aCol[] entry.
4184 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
4185 pExpr
->pAggInfo
= pAggInfo
;
4186 pExpr
->op
= TK_AGG_COLUMN
;
4187 pExpr
->iAgg
= (i16
)k
;
4189 } /* endif pExpr->iTable==pItem->iCursor */
4190 } /* end loop over pSrcList */
4194 case TK_AGG_FUNCTION
: {
4195 if( (pNC
->ncFlags
& NC_InAggFunc
)==0
4196 && pWalker
->walkerDepth
==pExpr
->op2
4198 /* Check to see if pExpr is a duplicate of another aggregate
4199 ** function that is already in the pAggInfo structure
4201 struct AggInfo_func
*pItem
= pAggInfo
->aFunc
;
4202 for(i
=0; i
<pAggInfo
->nFunc
; i
++, pItem
++){
4203 if( sqlite3ExprCompare(pItem
->pExpr
, pExpr
, -1)==0 ){
4207 if( i
>=pAggInfo
->nFunc
){
4208 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4210 u8 enc
= ENC(pParse
->db
);
4211 i
= addAggInfoFunc(pParse
->db
, pAggInfo
);
4213 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
4214 pItem
= &pAggInfo
->aFunc
[i
];
4215 pItem
->pExpr
= pExpr
;
4216 pItem
->iMem
= ++pParse
->nMem
;
4217 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4218 pItem
->pFunc
= sqlite3FindFunction(pParse
->db
,
4219 pExpr
->u
.zToken
, sqlite3Strlen30(pExpr
->u
.zToken
),
4220 pExpr
->x
.pList
? pExpr
->x
.pList
->nExpr
: 0, enc
, 0);
4221 if( pExpr
->flags
& EP_Distinct
){
4222 pItem
->iDistinct
= pParse
->nTab
++;
4224 pItem
->iDistinct
= -1;
4228 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4230 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
4231 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
4232 pExpr
->iAgg
= (i16
)i
;
4233 pExpr
->pAggInfo
= pAggInfo
;
4236 return WRC_Continue
;
4240 return WRC_Continue
;
4242 static int analyzeAggregatesInSelect(Walker
*pWalker
, Select
*pSelect
){
4243 UNUSED_PARAMETER(pWalker
);
4244 UNUSED_PARAMETER(pSelect
);
4245 return WRC_Continue
;
4249 ** Analyze the pExpr expression looking for aggregate functions and
4250 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
4251 ** points to. Additional entries are made on the AggInfo object as
4254 ** This routine should only be called after the expression has been
4255 ** analyzed by sqlite3ResolveExprNames().
4257 void sqlite3ExprAnalyzeAggregates(NameContext
*pNC
, Expr
*pExpr
){
4259 memset(&w
, 0, sizeof(w
));
4260 w
.xExprCallback
= analyzeAggregate
;
4261 w
.xSelectCallback
= analyzeAggregatesInSelect
;
4263 assert( pNC
->pSrcList
!=0 );
4264 sqlite3WalkExpr(&w
, pExpr
);
4268 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4269 ** expression list. Return the number of errors.
4271 ** If an error is found, the analysis is cut short.
4273 void sqlite3ExprAnalyzeAggList(NameContext
*pNC
, ExprList
*pList
){
4274 struct ExprList_item
*pItem
;
4277 for(pItem
=pList
->a
, i
=0; i
<pList
->nExpr
; i
++, pItem
++){
4278 sqlite3ExprAnalyzeAggregates(pNC
, pItem
->pExpr
);
4284 ** Allocate a single new register for use to hold some intermediate result.
4286 int sqlite3GetTempReg(Parse
*pParse
){
4287 if( pParse
->nTempReg
==0 ){
4288 return ++pParse
->nMem
;
4290 return pParse
->aTempReg
[--pParse
->nTempReg
];
4294 ** Deallocate a register, making available for reuse for some other
4297 ** If a register is currently being used by the column cache, then
4298 ** the deallocation is deferred until the column cache line that uses
4299 ** the register becomes stale.
4301 void sqlite3ReleaseTempReg(Parse
*pParse
, int iReg
){
4302 if( iReg
&& pParse
->nTempReg
<ArraySize(pParse
->aTempReg
) ){
4304 struct yColCache
*p
;
4305 for(i
=0, p
=pParse
->aColCache
; i
<SQLITE_N_COLCACHE
; i
++, p
++){
4306 if( p
->iReg
==iReg
){
4311 pParse
->aTempReg
[pParse
->nTempReg
++] = iReg
;
4316 ** Allocate or deallocate a block of nReg consecutive registers
4318 int sqlite3GetTempRange(Parse
*pParse
, int nReg
){
4320 i
= pParse
->iRangeReg
;
4321 n
= pParse
->nRangeReg
;
4323 assert( !usedAsColumnCache(pParse
, i
, i
+n
-1) );
4324 pParse
->iRangeReg
+= nReg
;
4325 pParse
->nRangeReg
-= nReg
;
4328 pParse
->nMem
+= nReg
;
4332 void sqlite3ReleaseTempRange(Parse
*pParse
, int iReg
, int nReg
){
4333 sqlite3ExprCacheRemove(pParse
, iReg
, nReg
);
4334 if( nReg
>pParse
->nRangeReg
){
4335 pParse
->nRangeReg
= nReg
;
4336 pParse
->iRangeReg
= iReg
;
4341 ** Mark all temporary registers as being unavailable for reuse.
4343 void sqlite3ClearTempRegCache(Parse
*pParse
){
4344 pParse
->nTempReg
= 0;
4345 pParse
->nRangeReg
= 0;