4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
15 #include "sqliteInt.h"
17 /* Forward declarations */
18 static void exprCodeBetween(Parse
*,Expr
*,int,void(*)(Parse
*,Expr
*,int,int),int);
19 static int exprCodeVector(Parse
*pParse
, Expr
*p
, int *piToFree
);
22 ** Return the affinity character for a single column of a table.
24 char sqlite3TableColumnAffinity(const Table
*pTab
, int iCol
){
25 if( iCol
<0 || NEVER(iCol
>=pTab
->nCol
) ) return SQLITE_AFF_INTEGER
;
26 return pTab
->aCol
[iCol
].affinity
;
30 ** Return the 'affinity' of the expression pExpr if any.
32 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33 ** or a sub-select with a column as the return value, then the
34 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35 ** indicating no affinity for the expression.
37 ** i.e. the WHERE clause expressions in the following statements all
40 ** CREATE TABLE t1(a);
41 ** SELECT * FROM t1 WHERE a;
42 ** SELECT a AS b FROM t1 WHERE b;
43 ** SELECT * FROM t1 WHERE (select a from t1);
45 char sqlite3ExprAffinity(const Expr
*pExpr
){
48 while( 1 /* exit-by-break */ ){
49 if( op
==TK_COLUMN
|| (op
==TK_AGG_COLUMN
&& pExpr
->y
.pTab
!=0) ){
50 assert( ExprUseYTab(pExpr
) );
51 assert( pExpr
->y
.pTab
!=0 );
52 return sqlite3TableColumnAffinity(pExpr
->y
.pTab
, pExpr
->iColumn
);
55 assert( ExprUseXSelect(pExpr
) );
56 assert( pExpr
->x
.pSelect
!=0 );
57 assert( pExpr
->x
.pSelect
->pEList
!=0 );
58 assert( pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
!=0 );
59 return sqlite3ExprAffinity(pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
);
61 #ifndef SQLITE_OMIT_CAST
63 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
64 return sqlite3AffinityType(pExpr
->u
.zToken
, 0);
67 if( op
==TK_SELECT_COLUMN
){
68 assert( pExpr
->pLeft
!=0 && ExprUseXSelect(pExpr
->pLeft
) );
69 assert( pExpr
->iColumn
< pExpr
->iTable
);
70 assert( pExpr
->iColumn
>= 0 );
71 assert( pExpr
->iTable
==pExpr
->pLeft
->x
.pSelect
->pEList
->nExpr
);
72 return sqlite3ExprAffinity(
73 pExpr
->pLeft
->x
.pSelect
->pEList
->a
[pExpr
->iColumn
].pExpr
77 assert( ExprUseXList(pExpr
) );
78 return sqlite3ExprAffinity(pExpr
->x
.pList
->a
[0].pExpr
);
80 if( ExprHasProperty(pExpr
, EP_Skip
|EP_IfNullRow
) ){
81 assert( pExpr
->op
==TK_COLLATE
82 || pExpr
->op
==TK_IF_NULL_ROW
83 || (pExpr
->op
==TK_REGISTER
&& pExpr
->op2
==TK_IF_NULL_ROW
) );
88 if( op
!=TK_REGISTER
|| (op
= pExpr
->op2
)==TK_REGISTER
) break;
90 return pExpr
->affExpr
;
94 ** Make a guess at all the possible datatypes of the result that could
95 ** be returned by an expression. Return a bitmask indicating the answer:
101 ** If the expression must return NULL, then 0x00 is returned.
103 int sqlite3ExprDataType(const Expr
*pExpr
){
109 pExpr
= pExpr
->pLeft
;
126 case TK_AGG_FUNCTION
:
134 case TK_SELECT_COLUMN
:
136 int aff
= sqlite3ExprAffinity(pExpr
);
137 if( aff
>=SQLITE_AFF_NUMERIC
) return 0x05;
138 if( aff
==SQLITE_AFF_TEXT
) return 0x06;
144 ExprList
*pList
= pExpr
->x
.pList
;
145 assert( ExprUseXList(pExpr
) && pList
!=0 );
146 assert( pList
->nExpr
> 0);
147 for(ii
=1; ii
<pList
->nExpr
; ii
+=2){
148 res
|= sqlite3ExprDataType(pList
->a
[ii
].pExpr
);
150 if( pList
->nExpr
% 2 ){
151 res
|= sqlite3ExprDataType(pList
->a
[pList
->nExpr
-1].pExpr
);
158 } /* End of switch(op) */
159 } /* End of while(pExpr) */
164 ** Set the collating sequence for expression pExpr to be the collating
165 ** sequence named by pToken. Return a pointer to a new Expr node that
166 ** implements the COLLATE operator.
168 ** If a memory allocation error occurs, that fact is recorded in pParse->db
169 ** and the pExpr parameter is returned unchanged.
171 Expr
*sqlite3ExprAddCollateToken(
172 const Parse
*pParse
, /* Parsing context */
173 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
174 const Token
*pCollName
, /* Name of collating sequence */
175 int dequote
/* True to dequote pCollName */
177 if( pCollName
->n
>0 ){
178 Expr
*pNew
= sqlite3ExprAlloc(pParse
->db
, TK_COLLATE
, pCollName
, dequote
);
181 pNew
->flags
|= EP_Collate
|EP_Skip
;
187 Expr
*sqlite3ExprAddCollateString(
188 const Parse
*pParse
, /* Parsing context */
189 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
190 const char *zC
/* The collating sequence name */
194 sqlite3TokenInit(&s
, (char*)zC
);
195 return sqlite3ExprAddCollateToken(pParse
, pExpr
, &s
, 0);
199 ** Skip over any TK_COLLATE operators.
201 Expr
*sqlite3ExprSkipCollate(Expr
*pExpr
){
202 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
) ){
203 assert( pExpr
->op
==TK_COLLATE
);
204 pExpr
= pExpr
->pLeft
;
210 ** Skip over any TK_COLLATE operators and/or any unlikely()
211 ** or likelihood() or likely() functions at the root of an
214 Expr
*sqlite3ExprSkipCollateAndLikely(Expr
*pExpr
){
215 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
|EP_Unlikely
) ){
216 if( ExprHasProperty(pExpr
, EP_Unlikely
) ){
217 assert( ExprUseXList(pExpr
) );
218 assert( pExpr
->x
.pList
->nExpr
>0 );
219 assert( pExpr
->op
==TK_FUNCTION
);
220 pExpr
= pExpr
->x
.pList
->a
[0].pExpr
;
221 }else if( pExpr
->op
==TK_COLLATE
){
222 pExpr
= pExpr
->pLeft
;
231 ** Return the collation sequence for the expression pExpr. If
232 ** there is no defined collating sequence, return NULL.
234 ** See also: sqlite3ExprNNCollSeq()
236 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
237 ** default collation if pExpr has no defined collation.
239 ** The collating sequence might be determined by a COLLATE operator
240 ** or by the presence of a column with a defined collating sequence.
241 ** COLLATE operators take first precedence. Left operands take
242 ** precedence over right operands.
244 CollSeq
*sqlite3ExprCollSeq(Parse
*pParse
, const Expr
*pExpr
){
245 sqlite3
*db
= pParse
->db
;
247 const Expr
*p
= pExpr
;
250 if( op
==TK_REGISTER
) op
= p
->op2
;
251 if( (op
==TK_AGG_COLUMN
&& p
->y
.pTab
!=0)
252 || op
==TK_COLUMN
|| op
==TK_TRIGGER
255 assert( ExprUseYTab(p
) );
256 assert( p
->y
.pTab
!=0 );
257 if( (j
= p
->iColumn
)>=0 ){
258 const char *zColl
= sqlite3ColumnColl(&p
->y
.pTab
->aCol
[j
]);
259 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
263 if( op
==TK_CAST
|| op
==TK_UPLUS
){
268 assert( ExprUseXList(p
) );
269 p
= p
->x
.pList
->a
[0].pExpr
;
272 if( op
==TK_COLLATE
){
273 assert( !ExprHasProperty(p
, EP_IntValue
) );
274 pColl
= sqlite3GetCollSeq(pParse
, ENC(db
), 0, p
->u
.zToken
);
277 if( p
->flags
& EP_Collate
){
278 if( p
->pLeft
&& (p
->pLeft
->flags
& EP_Collate
)!=0 ){
281 Expr
*pNext
= p
->pRight
;
282 /* The Expr.x union is never used at the same time as Expr.pRight */
283 assert( !ExprUseXList(p
) || p
->x
.pList
==0 || p
->pRight
==0 );
284 if( ExprUseXList(p
) && p
->x
.pList
!=0 && !db
->mallocFailed
){
286 for(i
=0; i
<p
->x
.pList
->nExpr
; i
++){
287 if( ExprHasProperty(p
->x
.pList
->a
[i
].pExpr
, EP_Collate
) ){
288 pNext
= p
->x
.pList
->a
[i
].pExpr
;
299 if( sqlite3CheckCollSeq(pParse
, pColl
) ){
306 ** Return the collation sequence for the expression pExpr. If
307 ** there is no defined collating sequence, return a pointer to the
308 ** default collation sequence.
310 ** See also: sqlite3ExprCollSeq()
312 ** The sqlite3ExprCollSeq() routine works the same except that it
313 ** returns NULL if there is no defined collation.
315 CollSeq
*sqlite3ExprNNCollSeq(Parse
*pParse
, const Expr
*pExpr
){
316 CollSeq
*p
= sqlite3ExprCollSeq(pParse
, pExpr
);
317 if( p
==0 ) p
= pParse
->db
->pDfltColl
;
323 ** Return TRUE if the two expressions have equivalent collating sequences.
325 int sqlite3ExprCollSeqMatch(Parse
*pParse
, const Expr
*pE1
, const Expr
*pE2
){
326 CollSeq
*pColl1
= sqlite3ExprNNCollSeq(pParse
, pE1
);
327 CollSeq
*pColl2
= sqlite3ExprNNCollSeq(pParse
, pE2
);
328 return sqlite3StrICmp(pColl1
->zName
, pColl2
->zName
)==0;
332 ** pExpr is an operand of a comparison operator. aff2 is the
333 ** type affinity of the other operand. This routine returns the
334 ** type affinity that should be used for the comparison operator.
336 char sqlite3CompareAffinity(const Expr
*pExpr
, char aff2
){
337 char aff1
= sqlite3ExprAffinity(pExpr
);
338 if( aff1
>SQLITE_AFF_NONE
&& aff2
>SQLITE_AFF_NONE
){
339 /* Both sides of the comparison are columns. If one has numeric
340 ** affinity, use that. Otherwise use no affinity.
342 if( sqlite3IsNumericAffinity(aff1
) || sqlite3IsNumericAffinity(aff2
) ){
343 return SQLITE_AFF_NUMERIC
;
345 return SQLITE_AFF_BLOB
;
348 /* One side is a column, the other is not. Use the columns affinity. */
349 assert( aff1
<=SQLITE_AFF_NONE
|| aff2
<=SQLITE_AFF_NONE
);
350 return (aff1
<=SQLITE_AFF_NONE
? aff2
: aff1
) | SQLITE_AFF_NONE
;
355 ** pExpr is a comparison operator. Return the type affinity that should
356 ** be applied to both operands prior to doing the comparison.
358 static char comparisonAffinity(const Expr
*pExpr
){
360 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_IN
|| pExpr
->op
==TK_LT
||
361 pExpr
->op
==TK_GT
|| pExpr
->op
==TK_GE
|| pExpr
->op
==TK_LE
||
362 pExpr
->op
==TK_NE
|| pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
);
363 assert( pExpr
->pLeft
);
364 aff
= sqlite3ExprAffinity(pExpr
->pLeft
);
366 aff
= sqlite3CompareAffinity(pExpr
->pRight
, aff
);
367 }else if( ExprUseXSelect(pExpr
) ){
368 aff
= sqlite3CompareAffinity(pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
, aff
);
370 aff
= SQLITE_AFF_BLOB
;
376 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
377 ** idx_affinity is the affinity of an indexed column. Return true
378 ** if the index with affinity idx_affinity may be used to implement
379 ** the comparison in pExpr.
381 int sqlite3IndexAffinityOk(const Expr
*pExpr
, char idx_affinity
){
382 char aff
= comparisonAffinity(pExpr
);
383 if( aff
<SQLITE_AFF_TEXT
){
386 if( aff
==SQLITE_AFF_TEXT
){
387 return idx_affinity
==SQLITE_AFF_TEXT
;
389 return sqlite3IsNumericAffinity(idx_affinity
);
393 ** Return the P5 value that should be used for a binary comparison
394 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
396 static u8
binaryCompareP5(
397 const Expr
*pExpr1
, /* Left operand */
398 const Expr
*pExpr2
, /* Right operand */
399 int jumpIfNull
/* Extra flags added to P5 */
401 u8 aff
= (char)sqlite3ExprAffinity(pExpr2
);
402 aff
= (u8
)sqlite3CompareAffinity(pExpr1
, aff
) | (u8
)jumpIfNull
;
407 ** Return a pointer to the collation sequence that should be used by
408 ** a binary comparison operator comparing pLeft and pRight.
410 ** If the left hand expression has a collating sequence type, then it is
411 ** used. Otherwise the collation sequence for the right hand expression
412 ** is used, or the default (BINARY) if neither expression has a collating
415 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
416 ** it is not considered.
418 CollSeq
*sqlite3BinaryCompareCollSeq(
425 if( pLeft
->flags
& EP_Collate
){
426 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
427 }else if( pRight
&& (pRight
->flags
& EP_Collate
)!=0 ){
428 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
430 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
432 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
438 /* Expression p is a comparison operator. Return a collation sequence
439 ** appropriate for the comparison operator.
441 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
442 ** However, if the OP_Commuted flag is set, then the order of the operands
443 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
444 ** correct collating sequence is found.
446 CollSeq
*sqlite3ExprCompareCollSeq(Parse
*pParse
, const Expr
*p
){
447 if( ExprHasProperty(p
, EP_Commuted
) ){
448 return sqlite3BinaryCompareCollSeq(pParse
, p
->pRight
, p
->pLeft
);
450 return sqlite3BinaryCompareCollSeq(pParse
, p
->pLeft
, p
->pRight
);
455 ** Generate code for a comparison operator.
457 static int codeCompare(
458 Parse
*pParse
, /* The parsing (and code generating) context */
459 Expr
*pLeft
, /* The left operand */
460 Expr
*pRight
, /* The right operand */
461 int opcode
, /* The comparison opcode */
462 int in1
, int in2
, /* Register holding operands */
463 int dest
, /* Jump here if true. */
464 int jumpIfNull
, /* If true, jump if either operand is NULL */
465 int isCommuted
/* The comparison has been commuted */
471 if( pParse
->nErr
) return 0;
473 p4
= sqlite3BinaryCompareCollSeq(pParse
, pRight
, pLeft
);
475 p4
= sqlite3BinaryCompareCollSeq(pParse
, pLeft
, pRight
);
477 p5
= binaryCompareP5(pLeft
, pRight
, jumpIfNull
);
478 addr
= sqlite3VdbeAddOp4(pParse
->pVdbe
, opcode
, in2
, dest
, in1
,
479 (void*)p4
, P4_COLLSEQ
);
480 sqlite3VdbeChangeP5(pParse
->pVdbe
, (u8
)p5
);
485 ** Return true if expression pExpr is a vector, or false otherwise.
487 ** A vector is defined as any expression that results in two or more
488 ** columns of result. Every TK_VECTOR node is an vector because the
489 ** parser will not generate a TK_VECTOR with fewer than two entries.
490 ** But a TK_SELECT might be either a vector or a scalar. It is only
491 ** considered a vector if it has two or more result columns.
493 int sqlite3ExprIsVector(const Expr
*pExpr
){
494 return sqlite3ExprVectorSize(pExpr
)>1;
498 ** If the expression passed as the only argument is of type TK_VECTOR
499 ** return the number of expressions in the vector. Or, if the expression
500 ** is a sub-select, return the number of columns in the sub-select. For
501 ** any other type of expression, return 1.
503 int sqlite3ExprVectorSize(const Expr
*pExpr
){
505 if( op
==TK_REGISTER
) op
= pExpr
->op2
;
507 assert( ExprUseXList(pExpr
) );
508 return pExpr
->x
.pList
->nExpr
;
509 }else if( op
==TK_SELECT
){
510 assert( ExprUseXSelect(pExpr
) );
511 return pExpr
->x
.pSelect
->pEList
->nExpr
;
518 ** Return a pointer to a subexpression of pVector that is the i-th
519 ** column of the vector (numbered starting with 0). The caller must
520 ** ensure that i is within range.
522 ** If pVector is really a scalar (and "scalar" here includes subqueries
523 ** that return a single column!) then return pVector unmodified.
525 ** pVector retains ownership of the returned subexpression.
527 ** If the vector is a (SELECT ...) then the expression returned is
528 ** just the expression for the i-th term of the result set, and may
529 ** not be ready for evaluation because the table cursor has not yet
532 Expr
*sqlite3VectorFieldSubexpr(Expr
*pVector
, int i
){
533 assert( i
<sqlite3ExprVectorSize(pVector
) || pVector
->op
==TK_ERROR
);
534 if( sqlite3ExprIsVector(pVector
) ){
535 assert( pVector
->op2
==0 || pVector
->op
==TK_REGISTER
);
536 if( pVector
->op
==TK_SELECT
|| pVector
->op2
==TK_SELECT
){
537 assert( ExprUseXSelect(pVector
) );
538 return pVector
->x
.pSelect
->pEList
->a
[i
].pExpr
;
540 assert( ExprUseXList(pVector
) );
541 return pVector
->x
.pList
->a
[i
].pExpr
;
548 ** Compute and return a new Expr object which when passed to
549 ** sqlite3ExprCode() will generate all necessary code to compute
550 ** the iField-th column of the vector expression pVector.
552 ** It is ok for pVector to be a scalar (as long as iField==0).
553 ** In that case, this routine works like sqlite3ExprDup().
555 ** The caller owns the returned Expr object and is responsible for
556 ** ensuring that the returned value eventually gets freed.
558 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
559 ** then the returned object will reference pVector and so pVector must remain
560 ** valid for the life of the returned object. If pVector is a TK_VECTOR
561 ** or a scalar expression, then it can be deleted as soon as this routine
564 ** A trick to cause a TK_SELECT pVector to be deleted together with
565 ** the returned Expr object is to attach the pVector to the pRight field
566 ** of the returned TK_SELECT_COLUMN Expr object.
568 Expr
*sqlite3ExprForVectorField(
569 Parse
*pParse
, /* Parsing context */
570 Expr
*pVector
, /* The vector. List of expressions or a sub-SELECT */
571 int iField
, /* Which column of the vector to return */
572 int nField
/* Total number of columns in the vector */
575 if( pVector
->op
==TK_SELECT
){
576 assert( ExprUseXSelect(pVector
) );
577 /* The TK_SELECT_COLUMN Expr node:
579 ** pLeft: pVector containing TK_SELECT. Not deleted.
580 ** pRight: not used. But recursively deleted.
581 ** iColumn: Index of a column in pVector
582 ** iTable: 0 or the number of columns on the LHS of an assignment
583 ** pLeft->iTable: First in an array of register holding result, or 0
584 ** if the result is not yet computed.
586 ** sqlite3ExprDelete() specifically skips the recursive delete of
587 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
588 ** can be attached to pRight to cause this node to take ownership of
589 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
590 ** with the same pLeft pointer to the pVector, but only one of them
591 ** will own the pVector.
593 pRet
= sqlite3PExpr(pParse
, TK_SELECT_COLUMN
, 0, 0);
595 ExprSetProperty(pRet
, EP_FullSize
);
596 pRet
->iTable
= nField
;
597 pRet
->iColumn
= iField
;
598 pRet
->pLeft
= pVector
;
601 if( pVector
->op
==TK_VECTOR
){
603 assert( ExprUseXList(pVector
) );
604 ppVector
= &pVector
->x
.pList
->a
[iField
].pExpr
;
606 if( IN_RENAME_OBJECT
){
607 /* This must be a vector UPDATE inside a trigger */
612 pRet
= sqlite3ExprDup(pParse
->db
, pVector
, 0);
618 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
619 ** it. Return the register in which the result is stored (or, if the
620 ** sub-select returns more than one column, the first in an array
621 ** of registers in which the result is stored).
623 ** If pExpr is not a TK_SELECT expression, return 0.
625 static int exprCodeSubselect(Parse
*pParse
, Expr
*pExpr
){
627 #ifndef SQLITE_OMIT_SUBQUERY
628 if( pExpr
->op
==TK_SELECT
){
629 reg
= sqlite3CodeSubselect(pParse
, pExpr
);
636 ** Argument pVector points to a vector expression - either a TK_VECTOR
637 ** or TK_SELECT that returns more than one column. This function returns
638 ** the register number of a register that contains the value of
639 ** element iField of the vector.
641 ** If pVector is a TK_SELECT expression, then code for it must have
642 ** already been generated using the exprCodeSubselect() routine. In this
643 ** case parameter regSelect should be the first in an array of registers
644 ** containing the results of the sub-select.
646 ** If pVector is of type TK_VECTOR, then code for the requested field
647 ** is generated. In this case (*pRegFree) may be set to the number of
648 ** a temporary register to be freed by the caller before returning.
650 ** Before returning, output parameter (*ppExpr) is set to point to the
651 ** Expr object corresponding to element iElem of the vector.
653 static int exprVectorRegister(
654 Parse
*pParse
, /* Parse context */
655 Expr
*pVector
, /* Vector to extract element from */
656 int iField
, /* Field to extract from pVector */
657 int regSelect
, /* First in array of registers */
658 Expr
**ppExpr
, /* OUT: Expression element */
659 int *pRegFree
/* OUT: Temp register to free */
662 assert( op
==TK_VECTOR
|| op
==TK_REGISTER
|| op
==TK_SELECT
|| op
==TK_ERROR
);
663 if( op
==TK_REGISTER
){
664 *ppExpr
= sqlite3VectorFieldSubexpr(pVector
, iField
);
665 return pVector
->iTable
+iField
;
668 assert( ExprUseXSelect(pVector
) );
669 *ppExpr
= pVector
->x
.pSelect
->pEList
->a
[iField
].pExpr
;
670 return regSelect
+iField
;
673 assert( ExprUseXList(pVector
) );
674 *ppExpr
= pVector
->x
.pList
->a
[iField
].pExpr
;
675 return sqlite3ExprCodeTemp(pParse
, *ppExpr
, pRegFree
);
681 ** Expression pExpr is a comparison between two vector values. Compute
682 ** the result of the comparison (1, 0, or NULL) and write that
683 ** result into register dest.
685 ** The caller must satisfy the following preconditions:
687 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
688 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
689 ** otherwise: op==pExpr->op and p5==0
691 static void codeVectorCompare(
692 Parse
*pParse
, /* Code generator context */
693 Expr
*pExpr
, /* The comparison operation */
694 int dest
, /* Write results into this register */
695 u8 op
, /* Comparison operator */
696 u8 p5
/* SQLITE_NULLEQ or zero */
698 Vdbe
*v
= pParse
->pVdbe
;
699 Expr
*pLeft
= pExpr
->pLeft
;
700 Expr
*pRight
= pExpr
->pRight
;
701 int nLeft
= sqlite3ExprVectorSize(pLeft
);
707 int addrDone
= sqlite3VdbeMakeLabel(pParse
);
708 int isCommuted
= ExprHasProperty(pExpr
,EP_Commuted
);
710 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
711 if( pParse
->nErr
) return;
712 if( nLeft
!=sqlite3ExprVectorSize(pRight
) ){
713 sqlite3ErrorMsg(pParse
, "row value misused");
716 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_NE
717 || pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
718 || pExpr
->op
==TK_LT
|| pExpr
->op
==TK_GT
719 || pExpr
->op
==TK_LE
|| pExpr
->op
==TK_GE
721 assert( pExpr
->op
==op
|| (pExpr
->op
==TK_IS
&& op
==TK_EQ
)
722 || (pExpr
->op
==TK_ISNOT
&& op
==TK_NE
) );
723 assert( p5
==0 || pExpr
->op
!=op
);
724 assert( p5
==SQLITE_NULLEQ
|| pExpr
->op
==op
);
726 if( op
==TK_LE
) opx
= TK_LT
;
727 if( op
==TK_GE
) opx
= TK_GT
;
728 if( op
==TK_NE
) opx
= TK_EQ
;
730 regLeft
= exprCodeSubselect(pParse
, pLeft
);
731 regRight
= exprCodeSubselect(pParse
, pRight
);
733 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, dest
);
734 for(i
=0; 1 /*Loop exits by "break"*/; i
++){
735 int regFree1
= 0, regFree2
= 0;
736 Expr
*pL
= 0, *pR
= 0;
738 assert( i
>=0 && i
<nLeft
);
739 if( addrCmp
) sqlite3VdbeJumpHere(v
, addrCmp
);
740 r1
= exprVectorRegister(pParse
, pLeft
, i
, regLeft
, &pL
, ®Free1
);
741 r2
= exprVectorRegister(pParse
, pRight
, i
, regRight
, &pR
, ®Free2
);
742 addrCmp
= sqlite3VdbeCurrentAddr(v
);
743 codeCompare(pParse
, pL
, pR
, opx
, r1
, r2
, addrDone
, p5
, isCommuted
);
744 testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
745 testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
746 testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
747 testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
748 testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
749 testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
750 sqlite3ReleaseTempReg(pParse
, regFree1
);
751 sqlite3ReleaseTempReg(pParse
, regFree2
);
752 if( (opx
==TK_LT
|| opx
==TK_GT
) && i
<nLeft
-1 ){
753 addrCmp
= sqlite3VdbeAddOp0(v
, OP_ElseEq
);
754 testcase(opx
==TK_LT
); VdbeCoverageIf(v
,opx
==TK_LT
);
755 testcase(opx
==TK_GT
); VdbeCoverageIf(v
,opx
==TK_GT
);
757 if( p5
==SQLITE_NULLEQ
){
758 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
);
760 sqlite3VdbeAddOp3(v
, OP_ZeroOrNull
, r1
, dest
, r2
);
766 sqlite3VdbeAddOp2(v
, OP_NotNull
, dest
, addrDone
); VdbeCoverage(v
);
768 assert( op
==TK_LT
|| op
==TK_GT
|| op
==TK_LE
|| op
==TK_GE
);
769 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrDone
);
770 if( i
==nLeft
-2 ) opx
= op
;
773 sqlite3VdbeJumpHere(v
, addrCmp
);
774 sqlite3VdbeResolveLabel(v
, addrDone
);
776 sqlite3VdbeAddOp2(v
, OP_Not
, dest
, dest
);
780 #if SQLITE_MAX_EXPR_DEPTH>0
782 ** Check that argument nHeight is less than or equal to the maximum
783 ** expression depth allowed. If it is not, leave an error message in
786 int sqlite3ExprCheckHeight(Parse
*pParse
, int nHeight
){
788 int mxHeight
= pParse
->db
->aLimit
[SQLITE_LIMIT_EXPR_DEPTH
];
789 if( nHeight
>mxHeight
){
790 sqlite3ErrorMsg(pParse
,
791 "Expression tree is too large (maximum depth %d)", mxHeight
798 /* The following three functions, heightOfExpr(), heightOfExprList()
799 ** and heightOfSelect(), are used to determine the maximum height
800 ** of any expression tree referenced by the structure passed as the
803 ** If this maximum height is greater than the current value pointed
804 ** to by pnHeight, the second parameter, then set *pnHeight to that
807 static void heightOfExpr(const Expr
*p
, int *pnHeight
){
809 if( p
->nHeight
>*pnHeight
){
810 *pnHeight
= p
->nHeight
;
814 static void heightOfExprList(const ExprList
*p
, int *pnHeight
){
817 for(i
=0; i
<p
->nExpr
; i
++){
818 heightOfExpr(p
->a
[i
].pExpr
, pnHeight
);
822 static void heightOfSelect(const Select
*pSelect
, int *pnHeight
){
824 for(p
=pSelect
; p
; p
=p
->pPrior
){
825 heightOfExpr(p
->pWhere
, pnHeight
);
826 heightOfExpr(p
->pHaving
, pnHeight
);
827 heightOfExpr(p
->pLimit
, pnHeight
);
828 heightOfExprList(p
->pEList
, pnHeight
);
829 heightOfExprList(p
->pGroupBy
, pnHeight
);
830 heightOfExprList(p
->pOrderBy
, pnHeight
);
835 ** Set the Expr.nHeight variable in the structure passed as an
836 ** argument. An expression with no children, Expr.pList or
837 ** Expr.pSelect member has a height of 1. Any other expression
838 ** has a height equal to the maximum height of any other
839 ** referenced Expr plus one.
841 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
844 static void exprSetHeight(Expr
*p
){
845 int nHeight
= p
->pLeft
? p
->pLeft
->nHeight
: 0;
846 if( NEVER(p
->pRight
) && p
->pRight
->nHeight
>nHeight
){
847 nHeight
= p
->pRight
->nHeight
;
849 if( ExprUseXSelect(p
) ){
850 heightOfSelect(p
->x
.pSelect
, &nHeight
);
851 }else if( p
->x
.pList
){
852 heightOfExprList(p
->x
.pList
, &nHeight
);
853 p
->flags
|= EP_Propagate
& sqlite3ExprListFlags(p
->x
.pList
);
855 p
->nHeight
= nHeight
+ 1;
859 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
860 ** the height is greater than the maximum allowed expression depth,
861 ** leave an error in pParse.
863 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
866 void sqlite3ExprSetHeightAndFlags(Parse
*pParse
, Expr
*p
){
867 if( pParse
->nErr
) return;
869 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
873 ** Return the maximum height of any expression tree referenced
874 ** by the select statement passed as an argument.
876 int sqlite3SelectExprHeight(const Select
*p
){
878 heightOfSelect(p
, &nHeight
);
881 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
883 ** Propagate all EP_Propagate flags from the Expr.x.pList into
886 void sqlite3ExprSetHeightAndFlags(Parse
*pParse
, Expr
*p
){
887 if( pParse
->nErr
) return;
888 if( p
&& ExprUseXList(p
) && p
->x
.pList
){
889 p
->flags
|= EP_Propagate
& sqlite3ExprListFlags(p
->x
.pList
);
892 #define exprSetHeight(y)
893 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
896 ** Set the error offset for an Expr node, if possible.
898 void sqlite3ExprSetErrorOffset(Expr
*pExpr
, int iOfst
){
899 if( pExpr
==0 ) return;
900 if( NEVER(ExprUseWJoin(pExpr
)) ) return;
901 pExpr
->w
.iOfst
= iOfst
;
905 ** This routine is the core allocator for Expr nodes.
907 ** Construct a new expression node and return a pointer to it. Memory
908 ** for this node and for the pToken argument is a single allocation
909 ** obtained from sqlite3DbMalloc(). The calling function
910 ** is responsible for making sure the node eventually gets freed.
912 ** If dequote is true, then the token (if it exists) is dequoted.
913 ** If dequote is false, no dequoting is performed. The deQuote
914 ** parameter is ignored if pToken is NULL or if the token does not
915 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
916 ** then the EP_DblQuoted flag is set on the expression node.
918 ** Special case (tag-20240227-a): If op==TK_INTEGER and pToken points to
919 ** a string that can be translated into a 32-bit integer, then the token is
920 ** not stored in u.zToken. Instead, the integer values is written
921 ** into u.iValue and the EP_IntValue flag is set. No extra storage
922 ** is allocated to hold the integer text and the dequote flag is ignored.
923 ** See also tag-20240227-b.
925 Expr
*sqlite3ExprAlloc(
926 sqlite3
*db
, /* Handle for sqlite3DbMallocRawNN() */
927 int op
, /* Expression opcode */
928 const Token
*pToken
, /* Token argument. Might be NULL */
929 int dequote
/* True to dequote */
937 if( op
!=TK_INTEGER
|| pToken
->z
==0
938 || sqlite3GetInt32(pToken
->z
, &iValue
)==0 ){
939 nExtra
= pToken
->n
+1; /* tag-20240227-a */
943 pNew
= sqlite3DbMallocRawNN(db
, sizeof(Expr
)+nExtra
);
945 memset(pNew
, 0, sizeof(Expr
));
950 pNew
->flags
|= EP_IntValue
|EP_Leaf
|(iValue
?EP_IsTrue
:EP_IsFalse
);
951 pNew
->u
.iValue
= iValue
;
953 pNew
->u
.zToken
= (char*)&pNew
[1];
954 assert( pToken
->z
!=0 || pToken
->n
==0 );
955 if( pToken
->n
) memcpy(pNew
->u
.zToken
, pToken
->z
, pToken
->n
);
956 pNew
->u
.zToken
[pToken
->n
] = 0;
957 if( dequote
&& sqlite3Isquote(pNew
->u
.zToken
[0]) ){
958 sqlite3DequoteExpr(pNew
);
962 #if SQLITE_MAX_EXPR_DEPTH>0
970 ** Allocate a new expression node from a zero-terminated token that has
971 ** already been dequoted.
974 sqlite3
*db
, /* Handle for sqlite3DbMallocZero() (may be null) */
975 int op
, /* Expression opcode */
976 const char *zToken
/* Token argument. Might be NULL */
980 x
.n
= sqlite3Strlen30(zToken
);
981 return sqlite3ExprAlloc(db
, op
, &x
, 0);
985 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
987 ** If pRoot==NULL that means that a memory allocation error has occurred.
988 ** In that case, delete the subtrees pLeft and pRight.
990 void sqlite3ExprAttachSubtrees(
997 assert( db
->mallocFailed
);
998 sqlite3ExprDelete(db
, pLeft
);
999 sqlite3ExprDelete(db
, pRight
);
1001 assert( ExprUseXList(pRoot
) );
1002 assert( pRoot
->x
.pSelect
==0 );
1004 pRoot
->pRight
= pRight
;
1005 pRoot
->flags
|= EP_Propagate
& pRight
->flags
;
1006 #if SQLITE_MAX_EXPR_DEPTH>0
1007 pRoot
->nHeight
= pRight
->nHeight
+1;
1013 pRoot
->pLeft
= pLeft
;
1014 pRoot
->flags
|= EP_Propagate
& pLeft
->flags
;
1015 #if SQLITE_MAX_EXPR_DEPTH>0
1016 if( pLeft
->nHeight
>=pRoot
->nHeight
){
1017 pRoot
->nHeight
= pLeft
->nHeight
+1;
1025 ** Allocate an Expr node which joins as many as two subtrees.
1027 ** One or both of the subtrees can be NULL. Return a pointer to the new
1028 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1029 ** free the subtrees and return NULL.
1032 Parse
*pParse
, /* Parsing context */
1033 int op
, /* Expression opcode */
1034 Expr
*pLeft
, /* Left operand */
1035 Expr
*pRight
/* Right operand */
1038 p
= sqlite3DbMallocRawNN(pParse
->db
, sizeof(Expr
));
1040 memset(p
, 0, sizeof(Expr
));
1043 sqlite3ExprAttachSubtrees(pParse
->db
, p
, pLeft
, pRight
);
1044 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
1046 sqlite3ExprDelete(pParse
->db
, pLeft
);
1047 sqlite3ExprDelete(pParse
->db
, pRight
);
1053 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1054 ** do a memory allocation failure) then delete the pSelect object.
1056 void sqlite3PExprAddSelect(Parse
*pParse
, Expr
*pExpr
, Select
*pSelect
){
1058 pExpr
->x
.pSelect
= pSelect
;
1059 ExprSetProperty(pExpr
, EP_xIsSelect
|EP_Subquery
);
1060 sqlite3ExprSetHeightAndFlags(pParse
, pExpr
);
1062 assert( pParse
->db
->mallocFailed
);
1063 sqlite3SelectDelete(pParse
->db
, pSelect
);
1068 ** Expression list pEList is a list of vector values. This function
1069 ** converts the contents of pEList to a VALUES(...) Select statement
1070 ** returning 1 row for each element of the list. For example, the
1073 ** ( (1,2), (3,4) (5,6) )
1075 ** is translated to the equivalent of:
1077 ** VALUES(1,2), (3,4), (5,6)
1079 ** Each of the vector values in pEList must contain exactly nElem terms.
1080 ** If a list element that is not a vector or does not contain nElem terms,
1081 ** an error message is left in pParse.
1083 ** This is used as part of processing IN(...) expressions with a list
1084 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1086 Select
*sqlite3ExprListToValues(Parse
*pParse
, int nElem
, ExprList
*pEList
){
1090 for(ii
=0; ii
<pEList
->nExpr
; ii
++){
1092 Expr
*pExpr
= pEList
->a
[ii
].pExpr
;
1094 if( pExpr
->op
==TK_VECTOR
){
1095 assert( ExprUseXList(pExpr
) );
1096 nExprElem
= pExpr
->x
.pList
->nExpr
;
1100 if( nExprElem
!=nElem
){
1101 sqlite3ErrorMsg(pParse
, "IN(...) element has %d term%s - expected %d",
1102 nExprElem
, nExprElem
>1?"s":"", nElem
1106 assert( ExprUseXList(pExpr
) );
1107 pSel
= sqlite3SelectNew(pParse
, pExpr
->x
.pList
, 0, 0, 0, 0, 0, SF_Values
,0);
1112 pSel
->pPrior
= pRet
;
1118 if( pRet
&& pRet
->pPrior
){
1119 pRet
->selFlags
|= SF_MultiValue
;
1121 sqlite3ExprListDelete(pParse
->db
, pEList
);
1126 ** Join two expressions using an AND operator. If either expression is
1127 ** NULL, then just return the other expression.
1129 ** If one side or the other of the AND is known to be false, and neither side
1130 ** is part of an ON clause, then instead of returning an AND expression,
1131 ** just return a constant expression with a value of false.
1133 Expr
*sqlite3ExprAnd(Parse
*pParse
, Expr
*pLeft
, Expr
*pRight
){
1134 sqlite3
*db
= pParse
->db
;
1137 }else if( pRight
==0 ){
1140 u32 f
= pLeft
->flags
| pRight
->flags
;
1141 if( (f
&(EP_OuterON
|EP_InnerON
|EP_IsFalse
))==EP_IsFalse
1142 && !IN_RENAME_OBJECT
1144 sqlite3ExprDeferredDelete(pParse
, pLeft
);
1145 sqlite3ExprDeferredDelete(pParse
, pRight
);
1146 return sqlite3Expr(db
, TK_INTEGER
, "0");
1148 return sqlite3PExpr(pParse
, TK_AND
, pLeft
, pRight
);
1154 ** Construct a new expression node for a function with multiple
1157 Expr
*sqlite3ExprFunction(
1158 Parse
*pParse
, /* Parsing context */
1159 ExprList
*pList
, /* Argument list */
1160 const Token
*pToken
, /* Name of the function */
1161 int eDistinct
/* SF_Distinct or SF_ALL or 0 */
1164 sqlite3
*db
= pParse
->db
;
1166 pNew
= sqlite3ExprAlloc(db
, TK_FUNCTION
, pToken
, 1);
1168 sqlite3ExprListDelete(db
, pList
); /* Avoid memory leak when malloc fails */
1171 assert( !ExprHasProperty(pNew
, EP_InnerON
|EP_OuterON
) );
1172 pNew
->w
.iOfst
= (int)(pToken
->z
- pParse
->zTail
);
1174 && pList
->nExpr
> pParse
->db
->aLimit
[SQLITE_LIMIT_FUNCTION_ARG
]
1177 sqlite3ErrorMsg(pParse
, "too many arguments on function %T", pToken
);
1179 pNew
->x
.pList
= pList
;
1180 ExprSetProperty(pNew
, EP_HasFunc
);
1181 assert( ExprUseXList(pNew
) );
1182 sqlite3ExprSetHeightAndFlags(pParse
, pNew
);
1183 if( eDistinct
==SF_Distinct
) ExprSetProperty(pNew
, EP_Distinct
);
1188 ** Report an error when attempting to use an ORDER BY clause within
1189 ** the arguments of a non-aggregate function.
1191 void sqlite3ExprOrderByAggregateError(Parse
*pParse
, Expr
*p
){
1192 sqlite3ErrorMsg(pParse
,
1193 "ORDER BY may not be used with non-aggregate %#T()", p
1198 ** Attach an ORDER BY clause to a function call.
1200 ** functionname( arguments ORDER BY sortlist )
1201 ** \_____________________/ \______/
1204 ** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER
1205 ** and added to the Expr.pLeft field of the parent TK_FUNCTION node.
1207 void sqlite3ExprAddFunctionOrderBy(
1208 Parse
*pParse
, /* Parsing context */
1209 Expr
*pExpr
, /* The function call to which ORDER BY is to be added */
1210 ExprList
*pOrderBy
/* The ORDER BY clause to add */
1213 sqlite3
*db
= pParse
->db
;
1214 if( NEVER(pOrderBy
==0) ){
1215 assert( db
->mallocFailed
);
1219 assert( db
->mallocFailed
);
1220 sqlite3ExprListDelete(db
, pOrderBy
);
1223 assert( pExpr
->op
==TK_FUNCTION
);
1224 assert( pExpr
->pLeft
==0 );
1225 assert( ExprUseXList(pExpr
) );
1226 if( pExpr
->x
.pList
==0 || NEVER(pExpr
->x
.pList
->nExpr
==0) ){
1227 /* Ignore ORDER BY on zero-argument aggregates */
1228 sqlite3ParserAddCleanup(pParse
, sqlite3ExprListDeleteGeneric
, pOrderBy
);
1231 if( IsWindowFunc(pExpr
) ){
1232 sqlite3ExprOrderByAggregateError(pParse
, pExpr
);
1233 sqlite3ExprListDelete(db
, pOrderBy
);
1237 pOB
= sqlite3ExprAlloc(db
, TK_ORDER
, 0, 0);
1239 sqlite3ExprListDelete(db
, pOrderBy
);
1242 pOB
->x
.pList
= pOrderBy
;
1243 assert( ExprUseXList(pOB
) );
1245 ExprSetProperty(pOB
, EP_FullSize
);
1249 ** Check to see if a function is usable according to current access
1252 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1254 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1257 ** If the function is not usable, create an error.
1259 void sqlite3ExprFunctionUsable(
1260 Parse
*pParse
, /* Parsing and code generating context */
1261 const Expr
*pExpr
, /* The function invocation */
1262 const FuncDef
*pDef
/* The function being invoked */
1264 assert( !IN_RENAME_OBJECT
);
1265 assert( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0 );
1266 if( ExprHasProperty(pExpr
, EP_FromDDL
) ){
1267 if( (pDef
->funcFlags
& SQLITE_FUNC_DIRECT
)!=0
1268 || (pParse
->db
->flags
& SQLITE_TrustedSchema
)==0
1270 /* Functions prohibited in triggers and views if:
1271 ** (1) tagged with SQLITE_DIRECTONLY
1272 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1273 ** is tagged with SQLITE_FUNC_UNSAFE) and
1274 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1275 ** that the schema is possibly tainted).
1277 sqlite3ErrorMsg(pParse
, "unsafe use of %#T()", pExpr
);
1283 ** Assign a variable number to an expression that encodes a wildcard
1284 ** in the original SQL statement.
1286 ** Wildcards consisting of a single "?" are assigned the next sequential
1289 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1290 ** sure "nnn" is not too big to avoid a denial of service attack when
1291 ** the SQL statement comes from an external source.
1293 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1294 ** as the previous instance of the same wildcard. Or if this is the first
1295 ** instance of the wildcard, the next sequential variable number is
1298 void sqlite3ExprAssignVarNumber(Parse
*pParse
, Expr
*pExpr
, u32 n
){
1299 sqlite3
*db
= pParse
->db
;
1303 if( pExpr
==0 ) return;
1304 assert( !ExprHasProperty(pExpr
, EP_IntValue
|EP_Reduced
|EP_TokenOnly
) );
1305 z
= pExpr
->u
.zToken
;
1308 assert( n
==(u32
)sqlite3Strlen30(z
) );
1310 /* Wildcard of the form "?". Assign the next variable number */
1311 assert( z
[0]=='?' );
1312 x
= (ynVar
)(++pParse
->nVar
);
1316 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1317 ** use it as the variable number */
1320 if( n
==2 ){ /*OPTIMIZATION-IF-TRUE*/
1321 i
= z
[1]-'0'; /* The common case of ?N for a single digit N */
1324 bOk
= 0==sqlite3Atoi64(&z
[1], &i
, n
-1, SQLITE_UTF8
);
1328 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]-1 );
1329 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] );
1330 if( bOk
==0 || i
<1 || i
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
1331 sqlite3ErrorMsg(pParse
, "variable number must be between ?1 and ?%d",
1332 db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]);
1333 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1337 if( x
>pParse
->nVar
){
1338 pParse
->nVar
= (int)x
;
1340 }else if( sqlite3VListNumToName(pParse
->pVList
, x
)==0 ){
1344 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1345 ** number as the prior appearance of the same name, or if the name
1346 ** has never appeared before, reuse the same variable number
1348 x
= (ynVar
)sqlite3VListNameToNum(pParse
->pVList
, z
, n
);
1350 x
= (ynVar
)(++pParse
->nVar
);
1355 pParse
->pVList
= sqlite3VListAdd(db
, pParse
->pVList
, z
, n
, x
);
1359 if( x
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
1360 sqlite3ErrorMsg(pParse
, "too many SQL variables");
1361 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1366 ** Recursively delete an expression tree.
1368 static SQLITE_NOINLINE
void sqlite3ExprDeleteNN(sqlite3
*db
, Expr
*p
){
1372 assert( !ExprUseUValue(p
) || p
->u
.iValue
>=0 );
1373 assert( !ExprUseYWin(p
) || !ExprUseYSub(p
) );
1374 assert( !ExprUseYWin(p
) || p
->y
.pWin
!=0 || db
->mallocFailed
);
1375 assert( p
->op
!=TK_FUNCTION
|| !ExprUseYSub(p
) );
1377 if( ExprHasProperty(p
, EP_Leaf
) && !ExprHasProperty(p
, EP_TokenOnly
) ){
1378 assert( p
->pLeft
==0 );
1379 assert( p
->pRight
==0 );
1380 assert( !ExprUseXSelect(p
) || p
->x
.pSelect
==0 );
1381 assert( !ExprUseXList(p
) || p
->x
.pList
==0 );
1384 if( !ExprHasProperty(p
, (EP_TokenOnly
|EP_Leaf
)) ){
1385 /* The Expr.x union is never used at the same time as Expr.pRight */
1386 assert( (ExprUseXList(p
) && p
->x
.pList
==0) || p
->pRight
==0 );
1388 assert( !ExprHasProperty(p
, EP_WinFunc
) );
1389 sqlite3ExprDeleteNN(db
, p
->pRight
);
1390 }else if( ExprUseXSelect(p
) ){
1391 assert( !ExprHasProperty(p
, EP_WinFunc
) );
1392 sqlite3SelectDelete(db
, p
->x
.pSelect
);
1394 sqlite3ExprListDelete(db
, p
->x
.pList
);
1395 #ifndef SQLITE_OMIT_WINDOWFUNC
1396 if( ExprHasProperty(p
, EP_WinFunc
) ){
1397 sqlite3WindowDelete(db
, p
->y
.pWin
);
1401 if( p
->pLeft
&& p
->op
!=TK_SELECT_COLUMN
){
1402 Expr
*pLeft
= p
->pLeft
;
1403 if( !ExprHasProperty(p
, EP_Static
)
1404 && !ExprHasProperty(pLeft
, EP_Static
)
1406 /* Avoid unnecessary recursion on unary operators */
1407 sqlite3DbNNFreeNN(db
, p
);
1409 goto exprDeleteRestart
;
1411 sqlite3ExprDeleteNN(db
, pLeft
);
1415 if( !ExprHasProperty(p
, EP_Static
) ){
1416 sqlite3DbNNFreeNN(db
, p
);
1419 void sqlite3ExprDelete(sqlite3
*db
, Expr
*p
){
1420 if( p
) sqlite3ExprDeleteNN(db
, p
);
1422 void sqlite3ExprDeleteGeneric(sqlite3
*db
, void *p
){
1423 if( ALWAYS(p
) ) sqlite3ExprDeleteNN(db
, (Expr
*)p
);
1427 ** Clear both elements of an OnOrUsing object
1429 void sqlite3ClearOnOrUsing(sqlite3
*db
, OnOrUsing
*p
){
1431 /* Nothing to clear */
1433 sqlite3ExprDeleteNN(db
, p
->pOn
);
1434 }else if( p
->pUsing
){
1435 sqlite3IdListDelete(db
, p
->pUsing
);
1440 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1441 ** This is similar to sqlite3ExprDelete() except that the delete is
1442 ** deferred until the pParse is deleted.
1444 ** The pExpr might be deleted immediately on an OOM error.
1446 ** Return 0 if the delete was successfully deferred. Return non-zero
1447 ** if the delete happened immediately because of an OOM.
1449 int sqlite3ExprDeferredDelete(Parse
*pParse
, Expr
*pExpr
){
1450 return 0==sqlite3ParserAddCleanup(pParse
, sqlite3ExprDeleteGeneric
, pExpr
);
1453 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1456 void sqlite3ExprUnmapAndDelete(Parse
*pParse
, Expr
*p
){
1458 if( IN_RENAME_OBJECT
){
1459 sqlite3RenameExprUnmap(pParse
, p
);
1461 sqlite3ExprDeleteNN(pParse
->db
, p
);
1466 ** Return the number of bytes allocated for the expression structure
1467 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1468 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1470 static int exprStructSize(const Expr
*p
){
1471 if( ExprHasProperty(p
, EP_TokenOnly
) ) return EXPR_TOKENONLYSIZE
;
1472 if( ExprHasProperty(p
, EP_Reduced
) ) return EXPR_REDUCEDSIZE
;
1473 return EXPR_FULLSIZE
;
1477 ** The dupedExpr*Size() routines each return the number of bytes required
1478 ** to store a copy of an expression or expression tree. They differ in
1479 ** how much of the tree is measured.
1481 ** dupedExprStructSize() Size of only the Expr structure
1482 ** dupedExprNodeSize() Size of Expr + space for token
1483 ** dupedExprSize() Expr + token + subtree components
1485 ***************************************************************************
1487 ** The dupedExprStructSize() function returns two values OR-ed together:
1488 ** (1) the space required for a copy of the Expr structure only and
1489 ** (2) the EP_xxx flags that indicate what the structure size should be.
1490 ** The return values is always one of:
1493 ** EXPR_REDUCEDSIZE | EP_Reduced
1494 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1496 ** The size of the structure can be found by masking the return value
1497 ** of this routine with 0xfff. The flags can be found by masking the
1498 ** return value with EP_Reduced|EP_TokenOnly.
1500 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1501 ** (unreduced) Expr objects as they or originally constructed by the parser.
1502 ** During expression analysis, extra information is computed and moved into
1503 ** later parts of the Expr object and that extra information might get chopped
1504 ** off if the expression is reduced. Note also that it does not work to
1505 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1506 ** to reduce a pristine expression tree from the parser. The implementation
1507 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1508 ** to enforce this constraint.
1510 static int dupedExprStructSize(const Expr
*p
, int flags
){
1512 assert( flags
==EXPRDUP_REDUCE
|| flags
==0 ); /* Only one flag value allowed */
1513 assert( EXPR_FULLSIZE
<=0xfff );
1514 assert( (0xfff & (EP_Reduced
|EP_TokenOnly
))==0 );
1515 if( 0==flags
|| ExprHasProperty(p
, EP_FullSize
) ){
1516 nSize
= EXPR_FULLSIZE
;
1518 assert( !ExprHasProperty(p
, EP_TokenOnly
|EP_Reduced
) );
1519 assert( !ExprHasProperty(p
, EP_OuterON
) );
1520 assert( !ExprHasVVAProperty(p
, EP_NoReduce
) );
1521 if( p
->pLeft
|| p
->x
.pList
){
1522 nSize
= EXPR_REDUCEDSIZE
| EP_Reduced
;
1524 assert( p
->pRight
==0 );
1525 nSize
= EXPR_TOKENONLYSIZE
| EP_TokenOnly
;
1532 ** This function returns the space in bytes required to store the copy
1533 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1534 ** string is defined.)
1536 static int dupedExprNodeSize(const Expr
*p
, int flags
){
1537 int nByte
= dupedExprStructSize(p
, flags
) & 0xfff;
1538 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1539 nByte
+= sqlite3Strlen30NN(p
->u
.zToken
)+1;
1541 return ROUND8(nByte
);
1545 ** Return the number of bytes required to create a duplicate of the
1546 ** expression passed as the first argument.
1548 ** The value returned includes space to create a copy of the Expr struct
1549 ** itself and the buffer referred to by Expr.u.zToken, if any.
1551 ** The return value includes space to duplicate all Expr nodes in the
1552 ** tree formed by Expr.pLeft and Expr.pRight, but not any other
1553 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
1555 static int dupedExprSize(const Expr
*p
){
1558 nByte
= dupedExprNodeSize(p
, EXPRDUP_REDUCE
);
1559 if( p
->pLeft
) nByte
+= dupedExprSize(p
->pLeft
);
1560 if( p
->pRight
) nByte
+= dupedExprSize(p
->pRight
);
1561 assert( nByte
==ROUND8(nByte
) );
1566 ** An EdupBuf is a memory allocation used to stored multiple Expr objects
1567 ** together with their Expr.zToken content. This is used to help implement
1568 ** compression while doing sqlite3ExprDup(). The top-level Expr does the
1569 ** allocation for itself and many of its decendents, then passes an instance
1570 ** of the structure down into exprDup() so that they decendents can have
1571 ** access to that memory.
1573 typedef struct EdupBuf EdupBuf
;
1575 u8
*zAlloc
; /* Memory space available for storage */
1577 u8
*zEnd
; /* First byte past the end of memory */
1582 ** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
1583 ** is not NULL then it points to memory that can be used to store a copy
1584 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf
1585 ** is updated with the new buffer tail prior to returning.
1587 static Expr
*exprDup(
1588 sqlite3
*db
, /* Database connection (for memory allocation) */
1589 const Expr
*p
, /* Expr tree to be duplicated */
1590 int dupFlags
, /* EXPRDUP_REDUCE for compression. 0 if not */
1591 EdupBuf
*pEdupBuf
/* Preallocated storage space, or NULL */
1593 Expr
*pNew
; /* Value to return */
1594 EdupBuf sEdupBuf
; /* Memory space from which to build Expr object */
1595 u32 staticFlag
; /* EP_Static if space not obtained from malloc */
1596 int nToken
= -1; /* Space needed for p->u.zToken. -1 means unknown */
1600 assert( dupFlags
==0 || dupFlags
==EXPRDUP_REDUCE
);
1601 assert( pEdupBuf
==0 || dupFlags
==EXPRDUP_REDUCE
);
1603 /* Figure out where to write the new Expr structure. */
1605 sEdupBuf
.zAlloc
= pEdupBuf
->zAlloc
;
1607 sEdupBuf
.zEnd
= pEdupBuf
->zEnd
;
1609 staticFlag
= EP_Static
;
1610 assert( sEdupBuf
.zAlloc
!=0 );
1611 assert( dupFlags
==EXPRDUP_REDUCE
);
1615 nAlloc
= dupedExprSize(p
);
1616 }else if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1617 nToken
= sqlite3Strlen30NN(p
->u
.zToken
)+1;
1618 nAlloc
= ROUND8(EXPR_FULLSIZE
+ nToken
);
1621 nAlloc
= ROUND8(EXPR_FULLSIZE
);
1623 assert( nAlloc
==ROUND8(nAlloc
) );
1624 sEdupBuf
.zAlloc
= sqlite3DbMallocRawNN(db
, nAlloc
);
1626 sEdupBuf
.zEnd
= sEdupBuf
.zAlloc
? sEdupBuf
.zAlloc
+nAlloc
: 0;
1631 pNew
= (Expr
*)sEdupBuf
.zAlloc
;
1632 assert( EIGHT_BYTE_ALIGNMENT(pNew
) );
1635 /* Set nNewSize to the size allocated for the structure pointed to
1636 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1637 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1638 ** by the copy of the p->u.zToken string (if any).
1640 const unsigned nStructSize
= dupedExprStructSize(p
, dupFlags
);
1641 int nNewSize
= nStructSize
& 0xfff;
1643 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1644 nToken
= sqlite3Strlen30(p
->u
.zToken
) + 1;
1650 assert( (int)(sEdupBuf
.zEnd
- sEdupBuf
.zAlloc
) >= nNewSize
+nToken
);
1651 assert( ExprHasProperty(p
, EP_Reduced
)==0 );
1652 memcpy(sEdupBuf
.zAlloc
, p
, nNewSize
);
1654 u32 nSize
= (u32
)exprStructSize(p
);
1655 assert( (int)(sEdupBuf
.zEnd
- sEdupBuf
.zAlloc
) >=
1656 (int)EXPR_FULLSIZE
+nToken
);
1657 memcpy(sEdupBuf
.zAlloc
, p
, nSize
);
1658 if( nSize
<EXPR_FULLSIZE
){
1659 memset(&sEdupBuf
.zAlloc
[nSize
], 0, EXPR_FULLSIZE
-nSize
);
1661 nNewSize
= EXPR_FULLSIZE
;
1664 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1665 pNew
->flags
&= ~(EP_Reduced
|EP_TokenOnly
|EP_Static
);
1666 pNew
->flags
|= nStructSize
& (EP_Reduced
|EP_TokenOnly
);
1667 pNew
->flags
|= staticFlag
;
1668 ExprClearVVAProperties(pNew
);
1670 ExprSetVVAProperty(pNew
, EP_Immutable
);
1673 /* Copy the p->u.zToken string, if any. */
1674 assert( nToken
>=0 );
1676 char *zToken
= pNew
->u
.zToken
= (char*)&sEdupBuf
.zAlloc
[nNewSize
];
1677 memcpy(zToken
, p
->u
.zToken
, nToken
);
1680 sEdupBuf
.zAlloc
+= ROUND8(nNewSize
);
1682 if( ((p
->flags
|pNew
->flags
)&(EP_TokenOnly
|EP_Leaf
))==0 ){
1684 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1685 if( ExprUseXSelect(p
) ){
1686 pNew
->x
.pSelect
= sqlite3SelectDup(db
, p
->x
.pSelect
, dupFlags
);
1688 pNew
->x
.pList
= sqlite3ExprListDup(db
, p
->x
.pList
,
1689 p
->op
!=TK_ORDER
? dupFlags
: 0);
1692 #ifndef SQLITE_OMIT_WINDOWFUNC
1693 if( ExprHasProperty(p
, EP_WinFunc
) ){
1694 pNew
->y
.pWin
= sqlite3WindowDup(db
, pNew
, p
->y
.pWin
);
1695 assert( ExprHasProperty(pNew
, EP_WinFunc
) );
1697 #endif /* SQLITE_OMIT_WINDOWFUNC */
1699 /* Fill in pNew->pLeft and pNew->pRight. */
1701 if( p
->op
==TK_SELECT_COLUMN
){
1702 pNew
->pLeft
= p
->pLeft
;
1703 assert( p
->pRight
==0
1704 || p
->pRight
==p
->pLeft
1705 || ExprHasProperty(p
->pLeft
, EP_Subquery
) );
1707 pNew
->pLeft
= p
->pLeft
?
1708 exprDup(db
, p
->pLeft
, EXPRDUP_REDUCE
, &sEdupBuf
) : 0;
1710 pNew
->pRight
= p
->pRight
?
1711 exprDup(db
, p
->pRight
, EXPRDUP_REDUCE
, &sEdupBuf
) : 0;
1713 if( p
->op
==TK_SELECT_COLUMN
){
1714 pNew
->pLeft
= p
->pLeft
;
1715 assert( p
->pRight
==0
1716 || p
->pRight
==p
->pLeft
1717 || ExprHasProperty(p
->pLeft
, EP_Subquery
) );
1719 pNew
->pLeft
= sqlite3ExprDup(db
, p
->pLeft
, 0);
1721 pNew
->pRight
= sqlite3ExprDup(db
, p
->pRight
, 0);
1725 if( pEdupBuf
) memcpy(pEdupBuf
, &sEdupBuf
, sizeof(sEdupBuf
));
1726 assert( sEdupBuf
.zAlloc
<= sEdupBuf
.zEnd
);
1731 ** Create and return a deep copy of the object passed as the second
1732 ** argument. If an OOM condition is encountered, NULL is returned
1733 ** and the db->mallocFailed flag set.
1735 #ifndef SQLITE_OMIT_CTE
1736 With
*sqlite3WithDup(sqlite3
*db
, With
*p
){
1739 sqlite3_int64 nByte
= sizeof(*p
) + sizeof(p
->a
[0]) * (p
->nCte
-1);
1740 pRet
= sqlite3DbMallocZero(db
, nByte
);
1743 pRet
->nCte
= p
->nCte
;
1744 for(i
=0; i
<p
->nCte
; i
++){
1745 pRet
->a
[i
].pSelect
= sqlite3SelectDup(db
, p
->a
[i
].pSelect
, 0);
1746 pRet
->a
[i
].pCols
= sqlite3ExprListDup(db
, p
->a
[i
].pCols
, 0);
1747 pRet
->a
[i
].zName
= sqlite3DbStrDup(db
, p
->a
[i
].zName
);
1748 pRet
->a
[i
].eM10d
= p
->a
[i
].eM10d
;
1755 # define sqlite3WithDup(x,y) 0
1758 #ifndef SQLITE_OMIT_WINDOWFUNC
1760 ** The gatherSelectWindows() procedure and its helper routine
1761 ** gatherSelectWindowsCallback() are used to scan all the expressions
1762 ** an a newly duplicated SELECT statement and gather all of the Window
1763 ** objects found there, assembling them onto the linked list at Select->pWin.
1765 static int gatherSelectWindowsCallback(Walker
*pWalker
, Expr
*pExpr
){
1766 if( pExpr
->op
==TK_FUNCTION
&& ExprHasProperty(pExpr
, EP_WinFunc
) ){
1767 Select
*pSelect
= pWalker
->u
.pSelect
;
1768 Window
*pWin
= pExpr
->y
.pWin
;
1770 assert( IsWindowFunc(pExpr
) );
1771 assert( pWin
->ppThis
==0 );
1772 sqlite3WindowLink(pSelect
, pWin
);
1774 return WRC_Continue
;
1776 static int gatherSelectWindowsSelectCallback(Walker
*pWalker
, Select
*p
){
1777 return p
==pWalker
->u
.pSelect
? WRC_Continue
: WRC_Prune
;
1779 static void gatherSelectWindows(Select
*p
){
1781 w
.xExprCallback
= gatherSelectWindowsCallback
;
1782 w
.xSelectCallback
= gatherSelectWindowsSelectCallback
;
1783 w
.xSelectCallback2
= 0;
1786 sqlite3WalkSelect(&w
, p
);
1792 ** The following group of routines make deep copies of expressions,
1793 ** expression lists, ID lists, and select statements. The copies can
1794 ** be deleted (by being passed to their respective ...Delete() routines)
1795 ** without effecting the originals.
1797 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1798 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1799 ** by subsequent calls to sqlite*ListAppend() routines.
1801 ** Any tables that the SrcList might point to are not duplicated.
1803 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1804 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1805 ** truncated version of the usual Expr structure that will be stored as
1806 ** part of the in-memory representation of the database schema.
1808 Expr
*sqlite3ExprDup(sqlite3
*db
, const Expr
*p
, int flags
){
1809 assert( flags
==0 || flags
==EXPRDUP_REDUCE
);
1810 return p
? exprDup(db
, p
, flags
, 0) : 0;
1812 ExprList
*sqlite3ExprListDup(sqlite3
*db
, const ExprList
*p
, int flags
){
1814 struct ExprList_item
*pItem
;
1815 const struct ExprList_item
*pOldItem
;
1817 Expr
*pPriorSelectColOld
= 0;
1818 Expr
*pPriorSelectColNew
= 0;
1820 if( p
==0 ) return 0;
1821 pNew
= sqlite3DbMallocRawNN(db
, sqlite3DbMallocSize(db
, p
));
1822 if( pNew
==0 ) return 0;
1823 pNew
->nExpr
= p
->nExpr
;
1824 pNew
->nAlloc
= p
->nAlloc
;
1827 for(i
=0; i
<p
->nExpr
; i
++, pItem
++, pOldItem
++){
1828 Expr
*pOldExpr
= pOldItem
->pExpr
;
1830 pItem
->pExpr
= sqlite3ExprDup(db
, pOldExpr
, flags
);
1832 && pOldExpr
->op
==TK_SELECT_COLUMN
1833 && (pNewExpr
= pItem
->pExpr
)!=0
1835 if( pNewExpr
->pRight
){
1836 pPriorSelectColOld
= pOldExpr
->pRight
;
1837 pPriorSelectColNew
= pNewExpr
->pRight
;
1838 pNewExpr
->pLeft
= pNewExpr
->pRight
;
1840 if( pOldExpr
->pLeft
!=pPriorSelectColOld
){
1841 pPriorSelectColOld
= pOldExpr
->pLeft
;
1842 pPriorSelectColNew
= sqlite3ExprDup(db
, pPriorSelectColOld
, flags
);
1843 pNewExpr
->pRight
= pPriorSelectColNew
;
1845 pNewExpr
->pLeft
= pPriorSelectColNew
;
1848 pItem
->zEName
= sqlite3DbStrDup(db
, pOldItem
->zEName
);
1849 pItem
->fg
= pOldItem
->fg
;
1851 pItem
->u
= pOldItem
->u
;
1857 ** If cursors, triggers, views and subqueries are all omitted from
1858 ** the build, then none of the following routines, except for
1859 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1860 ** called with a NULL argument.
1862 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1863 || !defined(SQLITE_OMIT_SUBQUERY)
1864 SrcList
*sqlite3SrcListDup(sqlite3
*db
, const SrcList
*p
, int flags
){
1869 if( p
==0 ) return 0;
1870 nByte
= sizeof(*p
) + (p
->nSrc
>0 ? sizeof(p
->a
[0]) * (p
->nSrc
-1) : 0);
1871 pNew
= sqlite3DbMallocRawNN(db
, nByte
);
1872 if( pNew
==0 ) return 0;
1873 pNew
->nSrc
= pNew
->nAlloc
= p
->nSrc
;
1874 for(i
=0; i
<p
->nSrc
; i
++){
1875 SrcItem
*pNewItem
= &pNew
->a
[i
];
1876 const SrcItem
*pOldItem
= &p
->a
[i
];
1878 pNewItem
->pSchema
= pOldItem
->pSchema
;
1879 pNewItem
->zDatabase
= sqlite3DbStrDup(db
, pOldItem
->zDatabase
);
1880 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1881 pNewItem
->zAlias
= sqlite3DbStrDup(db
, pOldItem
->zAlias
);
1882 pNewItem
->fg
= pOldItem
->fg
;
1883 pNewItem
->iCursor
= pOldItem
->iCursor
;
1884 pNewItem
->addrFillSub
= pOldItem
->addrFillSub
;
1885 pNewItem
->regReturn
= pOldItem
->regReturn
;
1886 pNewItem
->regResult
= pOldItem
->regResult
;
1887 if( pNewItem
->fg
.isIndexedBy
){
1888 pNewItem
->u1
.zIndexedBy
= sqlite3DbStrDup(db
, pOldItem
->u1
.zIndexedBy
);
1889 }else if( pNewItem
->fg
.isTabFunc
){
1890 pNewItem
->u1
.pFuncArg
=
1891 sqlite3ExprListDup(db
, pOldItem
->u1
.pFuncArg
, flags
);
1893 pNewItem
->u1
.nRow
= pOldItem
->u1
.nRow
;
1895 pNewItem
->u2
= pOldItem
->u2
;
1896 if( pNewItem
->fg
.isCte
){
1897 pNewItem
->u2
.pCteUse
->nUse
++;
1899 pTab
= pNewItem
->pTab
= pOldItem
->pTab
;
1903 pNewItem
->pSelect
= sqlite3SelectDup(db
, pOldItem
->pSelect
, flags
);
1904 if( pOldItem
->fg
.isUsing
){
1905 assert( pNewItem
->fg
.isUsing
);
1906 pNewItem
->u3
.pUsing
= sqlite3IdListDup(db
, pOldItem
->u3
.pUsing
);
1908 pNewItem
->u3
.pOn
= sqlite3ExprDup(db
, pOldItem
->u3
.pOn
, flags
);
1910 pNewItem
->colUsed
= pOldItem
->colUsed
;
1914 IdList
*sqlite3IdListDup(sqlite3
*db
, const IdList
*p
){
1918 if( p
==0 ) return 0;
1919 assert( p
->eU4
!=EU4_EXPR
);
1920 pNew
= sqlite3DbMallocRawNN(db
, sizeof(*pNew
)+(p
->nId
-1)*sizeof(p
->a
[0]) );
1921 if( pNew
==0 ) return 0;
1924 for(i
=0; i
<p
->nId
; i
++){
1925 struct IdList_item
*pNewItem
= &pNew
->a
[i
];
1926 const struct IdList_item
*pOldItem
= &p
->a
[i
];
1927 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1928 pNewItem
->u4
= pOldItem
->u4
;
1932 Select
*sqlite3SelectDup(sqlite3
*db
, const Select
*pDup
, int flags
){
1935 Select
**pp
= &pRet
;
1939 for(p
=pDup
; p
; p
=p
->pPrior
){
1940 Select
*pNew
= sqlite3DbMallocRawNN(db
, sizeof(*p
) );
1941 if( pNew
==0 ) break;
1942 pNew
->pEList
= sqlite3ExprListDup(db
, p
->pEList
, flags
);
1943 pNew
->pSrc
= sqlite3SrcListDup(db
, p
->pSrc
, flags
);
1944 pNew
->pWhere
= sqlite3ExprDup(db
, p
->pWhere
, flags
);
1945 pNew
->pGroupBy
= sqlite3ExprListDup(db
, p
->pGroupBy
, flags
);
1946 pNew
->pHaving
= sqlite3ExprDup(db
, p
->pHaving
, flags
);
1947 pNew
->pOrderBy
= sqlite3ExprListDup(db
, p
->pOrderBy
, flags
);
1949 pNew
->pNext
= pNext
;
1951 pNew
->pLimit
= sqlite3ExprDup(db
, p
->pLimit
, flags
);
1954 pNew
->selFlags
= p
->selFlags
& ~SF_UsesEphemeral
;
1955 pNew
->addrOpenEphm
[0] = -1;
1956 pNew
->addrOpenEphm
[1] = -1;
1957 pNew
->nSelectRow
= p
->nSelectRow
;
1958 pNew
->pWith
= sqlite3WithDup(db
, p
->pWith
);
1959 #ifndef SQLITE_OMIT_WINDOWFUNC
1961 pNew
->pWinDefn
= sqlite3WindowListDup(db
, p
->pWinDefn
);
1962 if( p
->pWin
&& db
->mallocFailed
==0 ) gatherSelectWindows(pNew
);
1964 pNew
->selId
= p
->selId
;
1965 if( db
->mallocFailed
){
1966 /* Any prior OOM might have left the Select object incomplete.
1967 ** Delete the whole thing rather than allow an incomplete Select
1968 ** to be used by the code generator. */
1970 sqlite3SelectDelete(db
, pNew
);
1981 Select
*sqlite3SelectDup(sqlite3
*db
, const Select
*p
, int flags
){
1989 ** Add a new element to the end of an expression list. If pList is
1990 ** initially NULL, then create a new expression list.
1992 ** The pList argument must be either NULL or a pointer to an ExprList
1993 ** obtained from a prior call to sqlite3ExprListAppend().
1995 ** If a memory allocation error occurs, the entire list is freed and
1996 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1997 ** that the new entry was successfully appended.
1999 static const struct ExprList_item zeroItem
= {0};
2000 SQLITE_NOINLINE ExprList
*sqlite3ExprListAppendNew(
2001 sqlite3
*db
, /* Database handle. Used for memory allocation */
2002 Expr
*pExpr
/* Expression to be appended. Might be NULL */
2004 struct ExprList_item
*pItem
;
2007 pList
= sqlite3DbMallocRawNN(db
, sizeof(ExprList
)+sizeof(pList
->a
[0])*4 );
2009 sqlite3ExprDelete(db
, pExpr
);
2014 pItem
= &pList
->a
[0];
2016 pItem
->pExpr
= pExpr
;
2019 SQLITE_NOINLINE ExprList
*sqlite3ExprListAppendGrow(
2020 sqlite3
*db
, /* Database handle. Used for memory allocation */
2021 ExprList
*pList
, /* List to which to append. Might be NULL */
2022 Expr
*pExpr
/* Expression to be appended. Might be NULL */
2024 struct ExprList_item
*pItem
;
2027 pNew
= sqlite3DbRealloc(db
, pList
,
2028 sizeof(*pList
)+(pList
->nAlloc
-1)*sizeof(pList
->a
[0]));
2030 sqlite3ExprListDelete(db
, pList
);
2031 sqlite3ExprDelete(db
, pExpr
);
2036 pItem
= &pList
->a
[pList
->nExpr
++];
2038 pItem
->pExpr
= pExpr
;
2041 ExprList
*sqlite3ExprListAppend(
2042 Parse
*pParse
, /* Parsing context */
2043 ExprList
*pList
, /* List to which to append. Might be NULL */
2044 Expr
*pExpr
/* Expression to be appended. Might be NULL */
2046 struct ExprList_item
*pItem
;
2048 return sqlite3ExprListAppendNew(pParse
->db
,pExpr
);
2050 if( pList
->nAlloc
<pList
->nExpr
+1 ){
2051 return sqlite3ExprListAppendGrow(pParse
->db
,pList
,pExpr
);
2053 pItem
= &pList
->a
[pList
->nExpr
++];
2055 pItem
->pExpr
= pExpr
;
2060 ** pColumns and pExpr form a vector assignment which is part of the SET
2061 ** clause of an UPDATE statement. Like this:
2063 ** (a,b,c) = (expr1,expr2,expr3)
2064 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
2066 ** For each term of the vector assignment, append new entries to the
2067 ** expression list pList. In the case of a subquery on the RHS, append
2068 ** TK_SELECT_COLUMN expressions.
2070 ExprList
*sqlite3ExprListAppendVector(
2071 Parse
*pParse
, /* Parsing context */
2072 ExprList
*pList
, /* List to which to append. Might be NULL */
2073 IdList
*pColumns
, /* List of names of LHS of the assignment */
2074 Expr
*pExpr
/* Vector expression to be appended. Might be NULL */
2076 sqlite3
*db
= pParse
->db
;
2079 int iFirst
= pList
? pList
->nExpr
: 0;
2080 /* pColumns can only be NULL due to an OOM but an OOM will cause an
2081 ** exit prior to this routine being invoked */
2082 if( NEVER(pColumns
==0) ) goto vector_append_error
;
2083 if( pExpr
==0 ) goto vector_append_error
;
2085 /* If the RHS is a vector, then we can immediately check to see that
2086 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
2087 ** wildcards ("*") in the result set of the SELECT must be expanded before
2088 ** we can do the size check, so defer the size check until code generation.
2090 if( pExpr
->op
!=TK_SELECT
&& pColumns
->nId
!=(n
=sqlite3ExprVectorSize(pExpr
)) ){
2091 sqlite3ErrorMsg(pParse
, "%d columns assigned %d values",
2093 goto vector_append_error
;
2096 for(i
=0; i
<pColumns
->nId
; i
++){
2097 Expr
*pSubExpr
= sqlite3ExprForVectorField(pParse
, pExpr
, i
, pColumns
->nId
);
2098 assert( pSubExpr
!=0 || db
->mallocFailed
);
2099 if( pSubExpr
==0 ) continue;
2100 pList
= sqlite3ExprListAppend(pParse
, pList
, pSubExpr
);
2102 assert( pList
->nExpr
==iFirst
+i
+1 );
2103 pList
->a
[pList
->nExpr
-1].zEName
= pColumns
->a
[i
].zName
;
2104 pColumns
->a
[i
].zName
= 0;
2108 if( !db
->mallocFailed
&& pExpr
->op
==TK_SELECT
&& ALWAYS(pList
!=0) ){
2109 Expr
*pFirst
= pList
->a
[iFirst
].pExpr
;
2110 assert( pFirst
!=0 );
2111 assert( pFirst
->op
==TK_SELECT_COLUMN
);
2113 /* Store the SELECT statement in pRight so it will be deleted when
2114 ** sqlite3ExprListDelete() is called */
2115 pFirst
->pRight
= pExpr
;
2118 /* Remember the size of the LHS in iTable so that we can check that
2119 ** the RHS and LHS sizes match during code generation. */
2120 pFirst
->iTable
= pColumns
->nId
;
2123 vector_append_error
:
2124 sqlite3ExprUnmapAndDelete(pParse
, pExpr
);
2125 sqlite3IdListDelete(db
, pColumns
);
2130 ** Set the sort order for the last element on the given ExprList.
2132 void sqlite3ExprListSetSortOrder(ExprList
*p
, int iSortOrder
, int eNulls
){
2133 struct ExprList_item
*pItem
;
2135 assert( p
->nExpr
>0 );
2137 assert( SQLITE_SO_UNDEFINED
<0 && SQLITE_SO_ASC
==0 && SQLITE_SO_DESC
>0 );
2138 assert( iSortOrder
==SQLITE_SO_UNDEFINED
2139 || iSortOrder
==SQLITE_SO_ASC
2140 || iSortOrder
==SQLITE_SO_DESC
2142 assert( eNulls
==SQLITE_SO_UNDEFINED
2143 || eNulls
==SQLITE_SO_ASC
2144 || eNulls
==SQLITE_SO_DESC
2147 pItem
= &p
->a
[p
->nExpr
-1];
2148 assert( pItem
->fg
.bNulls
==0 );
2149 if( iSortOrder
==SQLITE_SO_UNDEFINED
){
2150 iSortOrder
= SQLITE_SO_ASC
;
2152 pItem
->fg
.sortFlags
= (u8
)iSortOrder
;
2154 if( eNulls
!=SQLITE_SO_UNDEFINED
){
2155 pItem
->fg
.bNulls
= 1;
2156 if( iSortOrder
!=eNulls
){
2157 pItem
->fg
.sortFlags
|= KEYINFO_ORDER_BIGNULL
;
2163 ** Set the ExprList.a[].zEName element of the most recently added item
2164 ** on the expression list.
2166 ** pList might be NULL following an OOM error. But pName should never be
2167 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2170 void sqlite3ExprListSetName(
2171 Parse
*pParse
, /* Parsing context */
2172 ExprList
*pList
, /* List to which to add the span. */
2173 const Token
*pName
, /* Name to be added */
2174 int dequote
/* True to cause the name to be dequoted */
2176 assert( pList
!=0 || pParse
->db
->mallocFailed
!=0 );
2177 assert( pParse
->eParseMode
!=PARSE_MODE_UNMAP
|| dequote
==0 );
2179 struct ExprList_item
*pItem
;
2180 assert( pList
->nExpr
>0 );
2181 pItem
= &pList
->a
[pList
->nExpr
-1];
2182 assert( pItem
->zEName
==0 );
2183 assert( pItem
->fg
.eEName
==ENAME_NAME
);
2184 pItem
->zEName
= sqlite3DbStrNDup(pParse
->db
, pName
->z
, pName
->n
);
2186 /* If dequote==0, then pName->z does not point to part of a DDL
2187 ** statement handled by the parser. And so no token need be added
2188 ** to the token-map. */
2189 sqlite3Dequote(pItem
->zEName
);
2190 if( IN_RENAME_OBJECT
){
2191 sqlite3RenameTokenMap(pParse
, (const void*)pItem
->zEName
, pName
);
2198 ** Set the ExprList.a[].zSpan element of the most recently added item
2199 ** on the expression list.
2201 ** pList might be NULL following an OOM error. But pSpan should never be
2202 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2205 void sqlite3ExprListSetSpan(
2206 Parse
*pParse
, /* Parsing context */
2207 ExprList
*pList
, /* List to which to add the span. */
2208 const char *zStart
, /* Start of the span */
2209 const char *zEnd
/* End of the span */
2211 sqlite3
*db
= pParse
->db
;
2212 assert( pList
!=0 || db
->mallocFailed
!=0 );
2214 struct ExprList_item
*pItem
= &pList
->a
[pList
->nExpr
-1];
2215 assert( pList
->nExpr
>0 );
2216 if( pItem
->zEName
==0 ){
2217 pItem
->zEName
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
2218 pItem
->fg
.eEName
= ENAME_SPAN
;
2224 ** If the expression list pEList contains more than iLimit elements,
2225 ** leave an error message in pParse.
2227 void sqlite3ExprListCheckLength(
2232 int mx
= pParse
->db
->aLimit
[SQLITE_LIMIT_COLUMN
];
2233 testcase( pEList
&& pEList
->nExpr
==mx
);
2234 testcase( pEList
&& pEList
->nExpr
==mx
+1 );
2235 if( pEList
&& pEList
->nExpr
>mx
){
2236 sqlite3ErrorMsg(pParse
, "too many columns in %s", zObject
);
2241 ** Delete an entire expression list.
2243 static SQLITE_NOINLINE
void exprListDeleteNN(sqlite3
*db
, ExprList
*pList
){
2244 int i
= pList
->nExpr
;
2245 struct ExprList_item
*pItem
= pList
->a
;
2246 assert( pList
->nExpr
>0 );
2249 sqlite3ExprDelete(db
, pItem
->pExpr
);
2250 if( pItem
->zEName
) sqlite3DbNNFreeNN(db
, pItem
->zEName
);
2253 sqlite3DbNNFreeNN(db
, pList
);
2255 void sqlite3ExprListDelete(sqlite3
*db
, ExprList
*pList
){
2256 if( pList
) exprListDeleteNN(db
, pList
);
2258 void sqlite3ExprListDeleteGeneric(sqlite3
*db
, void *pList
){
2259 if( ALWAYS(pList
) ) exprListDeleteNN(db
, (ExprList
*)pList
);
2263 ** Return the bitwise-OR of all Expr.flags fields in the given
2266 u32
sqlite3ExprListFlags(const ExprList
*pList
){
2270 for(i
=0; i
<pList
->nExpr
; i
++){
2271 Expr
*pExpr
= pList
->a
[i
].pExpr
;
2279 ** This is a SELECT-node callback for the expression walker that
2280 ** always "fails". By "fail" in this case, we mean set
2281 ** pWalker->eCode to zero and abort.
2283 ** This callback is used by multiple expression walkers.
2285 int sqlite3SelectWalkFail(Walker
*pWalker
, Select
*NotUsed
){
2286 UNUSED_PARAMETER(NotUsed
);
2292 ** Check the input string to see if it is "true" or "false" (in any case).
2294 ** If the string is.... Return
2296 ** "false" EP_IsFalse
2299 u32
sqlite3IsTrueOrFalse(const char *zIn
){
2300 if( sqlite3StrICmp(zIn
, "true")==0 ) return EP_IsTrue
;
2301 if( sqlite3StrICmp(zIn
, "false")==0 ) return EP_IsFalse
;
2307 ** If the input expression is an ID with the name "true" or "false"
2308 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2309 ** the conversion happened, and zero if the expression is unaltered.
2311 int sqlite3ExprIdToTrueFalse(Expr
*pExpr
){
2313 assert( pExpr
->op
==TK_ID
|| pExpr
->op
==TK_STRING
);
2314 if( !ExprHasProperty(pExpr
, EP_Quoted
|EP_IntValue
)
2315 && (v
= sqlite3IsTrueOrFalse(pExpr
->u
.zToken
))!=0
2317 pExpr
->op
= TK_TRUEFALSE
;
2318 ExprSetProperty(pExpr
, v
);
2325 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2326 ** and 0 if it is FALSE.
2328 int sqlite3ExprTruthValue(const Expr
*pExpr
){
2329 pExpr
= sqlite3ExprSkipCollateAndLikely((Expr
*)pExpr
);
2330 assert( pExpr
->op
==TK_TRUEFALSE
);
2331 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2332 assert( sqlite3StrICmp(pExpr
->u
.zToken
,"true")==0
2333 || sqlite3StrICmp(pExpr
->u
.zToken
,"false")==0 );
2334 return pExpr
->u
.zToken
[4]==0;
2338 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2339 ** terms that are always true or false. Return the simplified expression.
2340 ** Or return the original expression if no simplification is possible.
2344 ** (x<10) AND true => (x<10)
2345 ** (x<10) AND false => false
2346 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2347 ** (x<10) AND (y=22 OR true) => (x<10)
2348 ** (y=22) OR true => true
2350 Expr
*sqlite3ExprSimplifiedAndOr(Expr
*pExpr
){
2352 if( pExpr
->op
==TK_AND
|| pExpr
->op
==TK_OR
){
2353 Expr
*pRight
= sqlite3ExprSimplifiedAndOr(pExpr
->pRight
);
2354 Expr
*pLeft
= sqlite3ExprSimplifiedAndOr(pExpr
->pLeft
);
2355 if( ExprAlwaysTrue(pLeft
) || ExprAlwaysFalse(pRight
) ){
2356 pExpr
= pExpr
->op
==TK_AND
? pRight
: pLeft
;
2357 }else if( ExprAlwaysTrue(pRight
) || ExprAlwaysFalse(pLeft
) ){
2358 pExpr
= pExpr
->op
==TK_AND
? pLeft
: pRight
;
2365 ** pExpr is a TK_FUNCTION node. Try to determine whether or not the
2366 ** function is a constant function. A function is constant if all of
2367 ** the following are true:
2369 ** (1) It is a scalar function (not an aggregate or window function)
2370 ** (2) It has either the SQLITE_FUNC_CONSTANT or SQLITE_FUNC_SLOCHNG
2372 ** (3) All of its arguments are constants
2374 ** This routine sets pWalker->eCode to 0 if pExpr is not a constant.
2375 ** It makes no changes to pWalker->eCode if pExpr is constant. In
2376 ** every case, it returns WRC_Abort.
2378 ** Called as a service subroutine from exprNodeIsConstant().
2380 static SQLITE_NOINLINE
int exprNodeIsConstantFunction(
2384 int n
; /* Number of arguments */
2385 ExprList
*pList
; /* List of arguments */
2386 FuncDef
*pDef
; /* The function */
2387 sqlite3
*db
; /* The database */
2389 assert( pExpr
->op
==TK_FUNCTION
);
2390 if( ExprHasProperty(pExpr
, EP_TokenOnly
)
2391 || (pList
= pExpr
->x
.pList
)==0
2396 sqlite3WalkExprList(pWalker
, pList
);
2397 if( pWalker
->eCode
==0 ) return WRC_Abort
;
2399 db
= pWalker
->pParse
->db
;
2400 pDef
= sqlite3FindFunction(db
, pExpr
->u
.zToken
, n
, ENC(db
), 0);
2402 || pDef
->xFinalize
!=0
2403 || (pDef
->funcFlags
& (SQLITE_FUNC_CONSTANT
|SQLITE_FUNC_SLOCHNG
))==0
2404 || ExprHasProperty(pExpr
, EP_WinFunc
)
2414 ** These routines are Walker callbacks used to check expressions to
2415 ** see if they are "constant" for some definition of constant. The
2416 ** Walker.eCode value determines the type of "constant" we are looking
2419 ** These callback routines are used to implement the following:
2421 ** sqlite3ExprIsConstant() pWalker->eCode==1
2422 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2423 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2424 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2426 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2427 ** is found to not be a constant.
2429 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2430 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2431 ** when parsing an existing schema out of the sqlite_schema table and 4
2432 ** when processing a new CREATE TABLE statement. A bound parameter raises
2433 ** an error for new statements, but is silently converted
2434 ** to NULL for existing schemas. This allows sqlite_schema tables that
2435 ** contain a bound parameter because they were generated by older versions
2436 ** of SQLite to be parsed by newer versions of SQLite without raising a
2437 ** malformed schema error.
2439 static int exprNodeIsConstant(Walker
*pWalker
, Expr
*pExpr
){
2440 assert( pWalker
->eCode
>0 );
2442 /* If pWalker->eCode is 2 then any term of the expression that comes from
2443 ** the ON or USING clauses of an outer join disqualifies the expression
2444 ** from being considered constant. */
2445 if( pWalker
->eCode
==2 && ExprHasProperty(pExpr
, EP_OuterON
) ){
2450 switch( pExpr
->op
){
2451 /* Consider functions to be constant if all their arguments are constant
2452 ** and either pWalker->eCode==4 or 5 or the function has the
2453 ** SQLITE_FUNC_CONST flag. */
2455 if( (pWalker
->eCode
>=4 || ExprHasProperty(pExpr
,EP_ConstFunc
))
2456 && !ExprHasProperty(pExpr
, EP_WinFunc
)
2458 if( pWalker
->eCode
==5 ) ExprSetProperty(pExpr
, EP_FromDDL
);
2459 return WRC_Continue
;
2460 }else if( pWalker
->pParse
){
2461 return exprNodeIsConstantFunction(pWalker
, pExpr
);
2467 /* Convert "true" or "false" in a DEFAULT clause into the
2468 ** appropriate TK_TRUEFALSE operator */
2469 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
2472 /* no break */ deliberate_fall_through
2474 case TK_AGG_FUNCTION
:
2476 testcase( pExpr
->op
==TK_ID
);
2477 testcase( pExpr
->op
==TK_COLUMN
);
2478 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
2479 testcase( pExpr
->op
==TK_AGG_COLUMN
);
2480 if( ExprHasProperty(pExpr
, EP_FixedCol
) && pWalker
->eCode
!=2 ){
2481 return WRC_Continue
;
2483 if( pWalker
->eCode
==3 && pExpr
->iTable
==pWalker
->u
.iCur
){
2484 return WRC_Continue
;
2486 /* no break */ deliberate_fall_through
2487 case TK_IF_NULL_ROW
:
2491 testcase( pExpr
->op
==TK_REGISTER
);
2492 testcase( pExpr
->op
==TK_IF_NULL_ROW
);
2493 testcase( pExpr
->op
==TK_DOT
);
2494 testcase( pExpr
->op
==TK_RAISE
);
2498 if( pWalker
->eCode
==5 ){
2499 /* Silently convert bound parameters that appear inside of CREATE
2500 ** statements into a NULL when parsing the CREATE statement text out
2501 ** of the sqlite_schema table */
2502 pExpr
->op
= TK_NULL
;
2503 }else if( pWalker
->eCode
==4 ){
2504 /* A bound parameter in a CREATE statement that originates from
2505 ** sqlite3_prepare() causes an error */
2509 /* no break */ deliberate_fall_through
2511 testcase( pExpr
->op
==TK_SELECT
); /* sqlite3SelectWalkFail() disallows */
2512 testcase( pExpr
->op
==TK_EXISTS
); /* sqlite3SelectWalkFail() disallows */
2513 return WRC_Continue
;
2516 static int exprIsConst(Parse
*pParse
, Expr
*p
, int initFlag
){
2520 w
.xExprCallback
= exprNodeIsConstant
;
2521 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2523 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2525 sqlite3WalkExpr(&w
, p
);
2530 ** Walk an expression tree. Return non-zero if the expression is constant
2531 ** and 0 if it involves variables or function calls.
2533 ** For the purposes of this function, a double-quoted string (ex: "abc")
2534 ** is considered a variable but a single-quoted string (ex: 'abc') is
2537 ** The pParse parameter may be NULL. But if it is NULL, there is no way
2538 ** to determine if function calls are constant or not, and hence all
2539 ** function calls will be considered to be non-constant. If pParse is
2540 ** not NULL, then a function call might be constant, depending on the
2541 ** function and on its parameters.
2543 int sqlite3ExprIsConstant(Parse
*pParse
, Expr
*p
){
2544 return exprIsConst(pParse
, p
, 1);
2548 ** Walk an expression tree. Return non-zero if
2550 ** (1) the expression is constant, and
2551 ** (2) the expression does originate in the ON or USING clause
2552 ** of a LEFT JOIN, and
2553 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2554 ** operands created by the constant propagation optimization.
2556 ** When this routine returns true, it indicates that the expression
2557 ** can be added to the pParse->pConstExpr list and evaluated once when
2558 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2560 static int sqlite3ExprIsConstantNotJoin(Parse
*pParse
, Expr
*p
){
2561 return exprIsConst(pParse
, p
, 2);
2565 ** This routine examines sub-SELECT statements as an expression is being
2566 ** walked as part of sqlite3ExprIsTableConstant(). Sub-SELECTs are considered
2567 ** constant as long as they are uncorrelated - meaning that they do not
2568 ** contain any terms from outer contexts.
2570 static int exprSelectWalkTableConstant(Walker
*pWalker
, Select
*pSelect
){
2571 assert( pSelect
!=0 );
2572 assert( pWalker
->eCode
==3 || pWalker
->eCode
==0 );
2573 if( (pSelect
->selFlags
& SF_Correlated
)!=0 ){
2581 ** Walk an expression tree. Return non-zero if the expression is constant
2582 ** for any single row of the table with cursor iCur. In other words, the
2583 ** expression must not refer to any non-deterministic function nor any
2584 ** table other than iCur.
2586 ** Consider uncorrelated subqueries to be constants if the bAllowSubq
2587 ** parameter is true.
2589 static int sqlite3ExprIsTableConstant(Expr
*p
, int iCur
, int bAllowSubq
){
2593 w
.xExprCallback
= exprNodeIsConstant
;
2595 w
.xSelectCallback
= exprSelectWalkTableConstant
;
2597 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2599 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2603 sqlite3WalkExpr(&w
, p
);
2608 ** Check pExpr to see if it is an constraint on the single data source
2609 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
2610 ** constrains pSrc but does not depend on any other tables or data
2611 ** sources anywhere else in the query. Return true (non-zero) if pExpr
2612 ** is a constraint on pSrc only.
2614 ** This is an optimization. False negatives will perhaps cause slower
2615 ** queries, but false positives will yield incorrect answers. So when in
2618 ** To be an single-source constraint, the following must be true:
2620 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2622 ** (2a) pExpr cannot use subqueries unless the bAllowSubq parameter is
2623 ** true and the subquery is non-correlated
2625 ** (2b) pExpr cannot use non-deterministic functions.
2627 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2628 ** (Is there some way to relax this constraint?)
2630 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2631 ** (4a) pExpr must come from an ON clause..
2632 ** (4b) and specifically the ON clause associated with the LEFT JOIN.
2634 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2635 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2636 ** clause, not an ON clause.
2640 ** (6a) pExpr does not originate in an ON or USING clause, or
2642 ** (6b) The ON or USING clause from which pExpr is derived is
2643 ** not to the left of a RIGHT JOIN (or FULL JOIN).
2645 ** Without this restriction, accepting pExpr as a single-table
2646 ** constraint might move the the ON/USING filter expression
2647 ** from the left side of a RIGHT JOIN over to the right side,
2648 ** which leads to incorrect answers. See also restriction (9)
2651 int sqlite3ExprIsSingleTableConstraint(
2652 Expr
*pExpr
, /* The constraint */
2653 const SrcList
*pSrcList
, /* Complete FROM clause */
2654 int iSrc
, /* Which element of pSrcList to use */
2655 int bAllowSubq
/* Allow non-correlated subqueries */
2657 const SrcItem
*pSrc
= &pSrcList
->a
[iSrc
];
2658 if( pSrc
->fg
.jointype
& JT_LTORJ
){
2659 return 0; /* rule (3) */
2661 if( pSrc
->fg
.jointype
& JT_LEFT
){
2662 if( !ExprHasProperty(pExpr
, EP_OuterON
) ) return 0; /* rule (4a) */
2663 if( pExpr
->w
.iJoin
!=pSrc
->iCursor
) return 0; /* rule (4b) */
2665 if( ExprHasProperty(pExpr
, EP_OuterON
) ) return 0; /* rule (5) */
2667 if( ExprHasProperty(pExpr
, EP_OuterON
|EP_InnerON
) /* (6a) */
2668 && (pSrcList
->a
[0].fg
.jointype
& JT_LTORJ
)!=0 /* Fast pre-test of (6b) */
2671 for(jj
=0; jj
<iSrc
; jj
++){
2672 if( pExpr
->w
.iJoin
==pSrcList
->a
[jj
].iCursor
){
2673 if( (pSrcList
->a
[jj
].fg
.jointype
& JT_LTORJ
)!=0 ){
2674 return 0; /* restriction (6) */
2680 /* Rules (1), (2a), and (2b) handled by the following: */
2681 return sqlite3ExprIsTableConstant(pExpr
, pSrc
->iCursor
, bAllowSubq
);
2686 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2688 static int exprNodeIsConstantOrGroupBy(Walker
*pWalker
, Expr
*pExpr
){
2689 ExprList
*pGroupBy
= pWalker
->u
.pGroupBy
;
2692 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2694 for(i
=0; i
<pGroupBy
->nExpr
; i
++){
2695 Expr
*p
= pGroupBy
->a
[i
].pExpr
;
2696 if( sqlite3ExprCompare(0, pExpr
, p
, -1)<2 ){
2697 CollSeq
*pColl
= sqlite3ExprNNCollSeq(pWalker
->pParse
, p
);
2698 if( sqlite3IsBinary(pColl
) ){
2704 /* Check if pExpr is a sub-select. If so, consider it variable. */
2705 if( ExprUseXSelect(pExpr
) ){
2710 return exprNodeIsConstant(pWalker
, pExpr
);
2714 ** Walk the expression tree passed as the first argument. Return non-zero
2715 ** if the expression consists entirely of constants or copies of terms
2716 ** in pGroupBy that sort with the BINARY collation sequence.
2718 ** This routine is used to determine if a term of the HAVING clause can
2719 ** be promoted into the WHERE clause. In order for such a promotion to work,
2720 ** the value of the HAVING clause term must be the same for all members of
2721 ** a "group". The requirement that the GROUP BY term must be BINARY
2722 ** assumes that no other collating sequence will have a finer-grained
2723 ** grouping than binary. In other words (A=B COLLATE binary) implies
2724 ** A=B in every other collating sequence. The requirement that the
2725 ** GROUP BY be BINARY is stricter than necessary. It would also work
2726 ** to promote HAVING clauses that use the same alternative collating
2727 ** sequence as the GROUP BY term, but that is much harder to check,
2728 ** alternative collating sequences are uncommon, and this is only an
2729 ** optimization, so we take the easy way out and simply require the
2730 ** GROUP BY to use the BINARY collating sequence.
2732 int sqlite3ExprIsConstantOrGroupBy(Parse
*pParse
, Expr
*p
, ExprList
*pGroupBy
){
2735 w
.xExprCallback
= exprNodeIsConstantOrGroupBy
;
2736 w
.xSelectCallback
= 0;
2737 w
.u
.pGroupBy
= pGroupBy
;
2739 sqlite3WalkExpr(&w
, p
);
2744 ** Walk an expression tree for the DEFAULT field of a column definition
2745 ** in a CREATE TABLE statement. Return non-zero if the expression is
2746 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2747 ** the expression is constant or a function call with constant arguments.
2748 ** Return and 0 if there are any variables.
2750 ** isInit is true when parsing from sqlite_schema. isInit is false when
2751 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2752 ** (such as ? or $abc) in the expression are converted into NULL. When
2753 ** isInit is false, parameters raise an error. Parameters should not be
2754 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2755 ** allowed it, so we need to support it when reading sqlite_schema for
2756 ** backwards compatibility.
2758 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2760 ** For the purposes of this function, a double-quoted string (ex: "abc")
2761 ** is considered a variable but a single-quoted string (ex: 'abc') is
2764 int sqlite3ExprIsConstantOrFunction(Expr
*p
, u8 isInit
){
2765 assert( isInit
==0 || isInit
==1 );
2766 return exprIsConst(0, p
, 4+isInit
);
2769 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2771 ** Walk an expression tree. Return 1 if the expression contains a
2772 ** subquery of some kind. Return 0 if there are no subqueries.
2774 int sqlite3ExprContainsSubquery(Expr
*p
){
2777 w
.xExprCallback
= sqlite3ExprWalkNoop
;
2778 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2780 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2782 sqlite3WalkExpr(&w
, p
);
2788 ** If the expression p codes a constant integer that is small enough
2789 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2790 ** in *pValue. If the expression is not an integer or if it is too big
2791 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2793 int sqlite3ExprIsInteger(const Expr
*p
, int *pValue
){
2795 if( NEVER(p
==0) ) return 0; /* Used to only happen following on OOM */
2797 /* If an expression is an integer literal that fits in a signed 32-bit
2798 ** integer, then the EP_IntValue flag will have already been set */
2799 assert( p
->op
!=TK_INTEGER
|| (p
->flags
& EP_IntValue
)!=0
2800 || sqlite3GetInt32(p
->u
.zToken
, &rc
)==0 );
2802 if( p
->flags
& EP_IntValue
){
2803 *pValue
= p
->u
.iValue
;
2808 rc
= sqlite3ExprIsInteger(p
->pLeft
, pValue
);
2813 if( sqlite3ExprIsInteger(p
->pLeft
, &v
) ){
2814 assert( ((unsigned int)v
)!=0x80000000 );
2826 ** Return FALSE if there is no chance that the expression can be NULL.
2828 ** If the expression might be NULL or if the expression is too complex
2829 ** to tell return TRUE.
2831 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2832 ** when we know that a value cannot be NULL. Hence, a false positive
2833 ** (returning TRUE when in fact the expression can never be NULL) might
2834 ** be a small performance hit but is otherwise harmless. On the other
2835 ** hand, a false negative (returning FALSE when the result could be NULL)
2836 ** will likely result in an incorrect answer. So when in doubt, return
2839 int sqlite3ExprCanBeNull(const Expr
*p
){
2842 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){
2847 if( op
==TK_REGISTER
) op
= p
->op2
;
2855 assert( ExprUseYTab(p
) );
2856 return ExprHasProperty(p
, EP_CanBeNull
)
2857 || NEVER(p
->y
.pTab
==0) /* Reference to column of index on expr */
2858 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
2859 || (p
->iColumn
==XN_ROWID
&& IsView(p
->y
.pTab
))
2862 && p
->y
.pTab
->aCol
!=0 /* Possible due to prior error */
2863 && ALWAYS(p
->iColumn
<p
->y
.pTab
->nCol
)
2864 && p
->y
.pTab
->aCol
[p
->iColumn
].notNull
==0);
2871 ** Return TRUE if the given expression is a constant which would be
2872 ** unchanged by OP_Affinity with the affinity given in the second
2875 ** This routine is used to determine if the OP_Affinity operation
2876 ** can be omitted. When in doubt return FALSE. A false negative
2877 ** is harmless. A false positive, however, can result in the wrong
2880 int sqlite3ExprNeedsNoAffinityChange(const Expr
*p
, char aff
){
2883 if( aff
==SQLITE_AFF_BLOB
) return 1;
2884 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){
2885 if( p
->op
==TK_UMINUS
) unaryMinus
= 1;
2889 if( op
==TK_REGISTER
) op
= p
->op2
;
2892 return aff
>=SQLITE_AFF_NUMERIC
;
2895 return aff
>=SQLITE_AFF_NUMERIC
;
2898 return !unaryMinus
&& aff
==SQLITE_AFF_TEXT
;
2904 assert( p
->iTable
>=0 ); /* p cannot be part of a CHECK constraint */
2905 return aff
>=SQLITE_AFF_NUMERIC
&& p
->iColumn
<0;
2914 ** Return TRUE if the given string is a row-id column name.
2916 int sqlite3IsRowid(const char *z
){
2917 if( sqlite3StrICmp(z
, "_ROWID_")==0 ) return 1;
2918 if( sqlite3StrICmp(z
, "ROWID")==0 ) return 1;
2919 if( sqlite3StrICmp(z
, "OID")==0 ) return 1;
2924 ** Return a pointer to a buffer containing a usable rowid alias for table
2925 ** pTab. An alias is usable if there is not an explicit user-defined column
2926 ** of the same name.
2928 const char *sqlite3RowidAlias(Table
*pTab
){
2929 const char *azOpt
[] = {"_ROWID_", "ROWID", "OID"};
2931 assert( VisibleRowid(pTab
) );
2932 for(ii
=0; ii
<ArraySize(azOpt
); ii
++){
2934 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
2935 if( sqlite3_stricmp(azOpt
[ii
], pTab
->aCol
[iCol
].zCnName
)==0 ) break;
2937 if( iCol
==pTab
->nCol
){
2945 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2946 ** that can be simplified to a direct table access, then return
2947 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2948 ** or if the SELECT statement needs to be materialized into a transient
2949 ** table, then return NULL.
2951 #ifndef SQLITE_OMIT_SUBQUERY
2952 static Select
*isCandidateForInOpt(const Expr
*pX
){
2958 if( !ExprUseXSelect(pX
) ) return 0; /* Not a subquery */
2959 if( ExprHasProperty(pX
, EP_VarSelect
) ) return 0; /* Correlated subq */
2961 if( p
->pPrior
) return 0; /* Not a compound SELECT */
2962 if( p
->selFlags
& (SF_Distinct
|SF_Aggregate
) ){
2963 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Distinct
);
2964 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Aggregate
);
2965 return 0; /* No DISTINCT keyword and no aggregate functions */
2967 assert( p
->pGroupBy
==0 ); /* Has no GROUP BY clause */
2968 if( p
->pLimit
) return 0; /* Has no LIMIT clause */
2969 if( p
->pWhere
) return 0; /* Has no WHERE clause */
2972 if( pSrc
->nSrc
!=1 ) return 0; /* Single term in FROM clause */
2973 if( pSrc
->a
[0].pSelect
) return 0; /* FROM is not a subquery or view */
2974 pTab
= pSrc
->a
[0].pTab
;
2976 assert( !IsView(pTab
) ); /* FROM clause is not a view */
2977 if( IsVirtual(pTab
) ) return 0; /* FROM clause not a virtual table */
2979 assert( pEList
!=0 );
2980 /* All SELECT results must be columns. */
2981 for(i
=0; i
<pEList
->nExpr
; i
++){
2982 Expr
*pRes
= pEList
->a
[i
].pExpr
;
2983 if( pRes
->op
!=TK_COLUMN
) return 0;
2984 assert( pRes
->iTable
==pSrc
->a
[0].iCursor
); /* Not a correlated subquery */
2988 #endif /* SQLITE_OMIT_SUBQUERY */
2990 #ifndef SQLITE_OMIT_SUBQUERY
2992 ** Generate code that checks the left-most column of index table iCur to see if
2993 ** it contains any NULL entries. Cause the register at regHasNull to be set
2994 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2995 ** to be set to NULL if iCur contains one or more NULL values.
2997 static void sqlite3SetHasNullFlag(Vdbe
*v
, int iCur
, int regHasNull
){
2999 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regHasNull
);
3000 addr1
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iCur
); VdbeCoverage(v
);
3001 sqlite3VdbeAddOp3(v
, OP_Column
, iCur
, 0, regHasNull
);
3002 sqlite3VdbeChangeP5(v
, OPFLAG_TYPEOFARG
);
3003 VdbeComment((v
, "first_entry_in(%d)", iCur
));
3004 sqlite3VdbeJumpHere(v
, addr1
);
3009 #ifndef SQLITE_OMIT_SUBQUERY
3011 ** The argument is an IN operator with a list (not a subquery) on the
3012 ** right-hand side. Return TRUE if that list is constant.
3014 static int sqlite3InRhsIsConstant(Parse
*pParse
, Expr
*pIn
){
3017 assert( !ExprHasProperty(pIn
, EP_xIsSelect
) );
3020 res
= sqlite3ExprIsConstant(pParse
, pIn
);
3027 ** This function is used by the implementation of the IN (...) operator.
3028 ** The pX parameter is the expression on the RHS of the IN operator, which
3029 ** might be either a list of expressions or a subquery.
3031 ** The job of this routine is to find or create a b-tree object that can
3032 ** be used either to test for membership in the RHS set or to iterate through
3033 ** all members of the RHS set, skipping duplicates.
3035 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
3036 ** and the *piTab parameter is set to the index of that cursor.
3038 ** The returned value of this function indicates the b-tree type, as follows:
3040 ** IN_INDEX_ROWID - The cursor was opened on a database table.
3041 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
3042 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
3043 ** IN_INDEX_EPH - The cursor was opened on a specially created and
3044 ** populated ephemeral table.
3045 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
3046 ** implemented as a sequence of comparisons.
3048 ** An existing b-tree might be used if the RHS expression pX is a simple
3049 ** subquery such as:
3051 ** SELECT <column1>, <column2>... FROM <table>
3053 ** If the RHS of the IN operator is a list or a more complex subquery, then
3054 ** an ephemeral table might need to be generated from the RHS and then
3055 ** pX->iTable made to point to the ephemeral table instead of an
3056 ** existing table. In this case, the creation and initialization of the
3057 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag
3058 ** will be set on pX and the pX->y.sub fields will be set to show where
3059 ** the subroutine is coded.
3061 ** The inFlags parameter must contain, at a minimum, one of the bits
3062 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
3063 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
3064 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
3065 ** be used to loop over all values of the RHS of the IN operator.
3067 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
3068 ** through the set members) then the b-tree must not contain duplicates.
3069 ** An ephemeral table will be created unless the selected columns are guaranteed
3070 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
3071 ** a UNIQUE constraint or index.
3073 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
3074 ** for fast set membership tests) then an ephemeral table must
3075 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
3076 ** index can be found with the specified <columns> as its left-most.
3078 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
3079 ** if the RHS of the IN operator is a list (not a subquery) then this
3080 ** routine might decide that creating an ephemeral b-tree for membership
3081 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
3082 ** calling routine should implement the IN operator using a sequence
3083 ** of Eq or Ne comparison operations.
3085 ** When the b-tree is being used for membership tests, the calling function
3086 ** might need to know whether or not the RHS side of the IN operator
3087 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
3088 ** if there is any chance that the (...) might contain a NULL value at
3089 ** runtime, then a register is allocated and the register number written
3090 ** to *prRhsHasNull. If there is no chance that the (...) contains a
3091 ** NULL value, then *prRhsHasNull is left unchanged.
3093 ** If a register is allocated and its location stored in *prRhsHasNull, then
3094 ** the value in that register will be NULL if the b-tree contains one or more
3095 ** NULL values, and it will be some non-NULL value if the b-tree contains no
3098 ** If the aiMap parameter is not NULL, it must point to an array containing
3099 ** one element for each column returned by the SELECT statement on the RHS
3100 ** of the IN(...) operator. The i'th entry of the array is populated with the
3101 ** offset of the index column that matches the i'th column returned by the
3102 ** SELECT. For example, if the expression and selected index are:
3104 ** (?,?,?) IN (SELECT a, b, c FROM t1)
3105 ** CREATE INDEX i1 ON t1(b, c, a);
3107 ** then aiMap[] is populated with {2, 0, 1}.
3109 #ifndef SQLITE_OMIT_SUBQUERY
3110 int sqlite3FindInIndex(
3111 Parse
*pParse
, /* Parsing context */
3112 Expr
*pX
, /* The IN expression */
3113 u32 inFlags
, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
3114 int *prRhsHasNull
, /* Register holding NULL status. See notes */
3115 int *aiMap
, /* Mapping from Index fields to RHS fields */
3116 int *piTab
/* OUT: index to use */
3118 Select
*p
; /* SELECT to the right of IN operator */
3119 int eType
= 0; /* Type of RHS table. IN_INDEX_* */
3120 int iTab
; /* Cursor of the RHS table */
3121 int mustBeUnique
; /* True if RHS must be unique */
3122 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Virtual machine being coded */
3124 assert( pX
->op
==TK_IN
);
3125 mustBeUnique
= (inFlags
& IN_INDEX_LOOP
)!=0;
3126 iTab
= pParse
->nTab
++;
3128 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
3129 ** whether or not the SELECT result contains NULL values, check whether
3130 ** or not NULL is actually possible (it may not be, for example, due
3131 ** to NOT NULL constraints in the schema). If no NULL values are possible,
3132 ** set prRhsHasNull to 0 before continuing. */
3133 if( prRhsHasNull
&& ExprUseXSelect(pX
) ){
3135 ExprList
*pEList
= pX
->x
.pSelect
->pEList
;
3136 for(i
=0; i
<pEList
->nExpr
; i
++){
3137 if( sqlite3ExprCanBeNull(pEList
->a
[i
].pExpr
) ) break;
3139 if( i
==pEList
->nExpr
){
3144 /* Check to see if an existing table or index can be used to
3145 ** satisfy the query. This is preferable to generating a new
3146 ** ephemeral table. */
3147 if( pParse
->nErr
==0 && (p
= isCandidateForInOpt(pX
))!=0 ){
3148 sqlite3
*db
= pParse
->db
; /* Database connection */
3149 Table
*pTab
; /* Table <table>. */
3150 int iDb
; /* Database idx for pTab */
3151 ExprList
*pEList
= p
->pEList
;
3152 int nExpr
= pEList
->nExpr
;
3154 assert( p
->pEList
!=0 ); /* Because of isCandidateForInOpt(p) */
3155 assert( p
->pEList
->a
[0].pExpr
!=0 ); /* Because of isCandidateForInOpt(p) */
3156 assert( p
->pSrc
!=0 ); /* Because of isCandidateForInOpt(p) */
3157 pTab
= p
->pSrc
->a
[0].pTab
;
3159 /* Code an OP_Transaction and OP_TableLock for <table>. */
3160 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
3161 assert( iDb
>=0 && iDb
<SQLITE_MAX_DB
);
3162 sqlite3CodeVerifySchema(pParse
, iDb
);
3163 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 0, pTab
->zName
);
3165 assert(v
); /* sqlite3GetVdbe() has always been previously called */
3166 if( nExpr
==1 && pEList
->a
[0].pExpr
->iColumn
<0 ){
3167 /* The "x IN (SELECT rowid FROM table)" case */
3168 int iAddr
= sqlite3VdbeAddOp0(v
, OP_Once
);
3171 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
3172 eType
= IN_INDEX_ROWID
;
3173 ExplainQueryPlan((pParse
, 0,
3174 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab
->zName
));
3175 sqlite3VdbeJumpHere(v
, iAddr
);
3177 Index
*pIdx
; /* Iterator variable */
3178 int affinity_ok
= 1;
3181 /* Check that the affinity that will be used to perform each
3182 ** comparison is the same as the affinity of each column in table
3183 ** on the RHS of the IN operator. If it not, it is not possible to
3184 ** use any index of the RHS table. */
3185 for(i
=0; i
<nExpr
&& affinity_ok
; i
++){
3186 Expr
*pLhs
= sqlite3VectorFieldSubexpr(pX
->pLeft
, i
);
3187 int iCol
= pEList
->a
[i
].pExpr
->iColumn
;
3188 char idxaff
= sqlite3TableColumnAffinity(pTab
,iCol
); /* RHS table */
3189 char cmpaff
= sqlite3CompareAffinity(pLhs
, idxaff
);
3190 testcase( cmpaff
==SQLITE_AFF_BLOB
);
3191 testcase( cmpaff
==SQLITE_AFF_TEXT
);
3193 case SQLITE_AFF_BLOB
:
3195 case SQLITE_AFF_TEXT
:
3196 /* sqlite3CompareAffinity() only returns TEXT if one side or the
3197 ** other has no affinity and the other side is TEXT. Hence,
3198 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
3199 ** and for the term on the LHS of the IN to have no affinity. */
3200 assert( idxaff
==SQLITE_AFF_TEXT
);
3203 affinity_ok
= sqlite3IsNumericAffinity(idxaff
);
3208 /* Search for an existing index that will work for this IN operator */
3209 for(pIdx
=pTab
->pIndex
; pIdx
&& eType
==0; pIdx
=pIdx
->pNext
){
3210 Bitmask colUsed
; /* Columns of the index used */
3211 Bitmask mCol
; /* Mask for the current column */
3212 if( pIdx
->nColumn
<nExpr
) continue;
3213 if( pIdx
->pPartIdxWhere
!=0 ) continue;
3214 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
3215 ** BITMASK(nExpr) without overflowing */
3216 testcase( pIdx
->nColumn
==BMS
-2 );
3217 testcase( pIdx
->nColumn
==BMS
-1 );
3218 if( pIdx
->nColumn
>=BMS
-1 ) continue;
3220 if( pIdx
->nKeyCol
>nExpr
3221 ||(pIdx
->nColumn
>nExpr
&& !IsUniqueIndex(pIdx
))
3223 continue; /* This index is not unique over the IN RHS columns */
3227 colUsed
= 0; /* Columns of index used so far */
3228 for(i
=0; i
<nExpr
; i
++){
3229 Expr
*pLhs
= sqlite3VectorFieldSubexpr(pX
->pLeft
, i
);
3230 Expr
*pRhs
= pEList
->a
[i
].pExpr
;
3231 CollSeq
*pReq
= sqlite3BinaryCompareCollSeq(pParse
, pLhs
, pRhs
);
3234 for(j
=0; j
<nExpr
; j
++){
3235 if( pIdx
->aiColumn
[j
]!=pRhs
->iColumn
) continue;
3236 assert( pIdx
->azColl
[j
] );
3237 if( pReq
!=0 && sqlite3StrICmp(pReq
->zName
, pIdx
->azColl
[j
])!=0 ){
3242 if( j
==nExpr
) break;
3244 if( mCol
& colUsed
) break; /* Each column used only once */
3246 if( aiMap
) aiMap
[i
] = j
;
3249 assert( i
==nExpr
|| colUsed
!=(MASKBIT(nExpr
)-1) );
3250 if( colUsed
==(MASKBIT(nExpr
)-1) ){
3251 /* If we reach this point, that means the index pIdx is usable */
3252 int iAddr
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3253 ExplainQueryPlan((pParse
, 0,
3254 "USING INDEX %s FOR IN-OPERATOR",pIdx
->zName
));
3255 sqlite3VdbeAddOp3(v
, OP_OpenRead
, iTab
, pIdx
->tnum
, iDb
);
3256 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
3257 VdbeComment((v
, "%s", pIdx
->zName
));
3258 assert( IN_INDEX_INDEX_DESC
== IN_INDEX_INDEX_ASC
+1 );
3259 eType
= IN_INDEX_INDEX_ASC
+ pIdx
->aSortOrder
[0];
3262 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3263 i64 mask
= (1<<nExpr
)-1;
3264 sqlite3VdbeAddOp4Dup8(v
, OP_ColumnsUsed
,
3265 iTab
, 0, 0, (u8
*)&mask
, P4_INT64
);
3267 *prRhsHasNull
= ++pParse
->nMem
;
3269 sqlite3SetHasNullFlag(v
, iTab
, *prRhsHasNull
);
3272 sqlite3VdbeJumpHere(v
, iAddr
);
3274 } /* End loop over indexes */
3275 } /* End if( affinity_ok ) */
3276 } /* End if not an rowid index */
3277 } /* End attempt to optimize using an index */
3279 /* If no preexisting index is available for the IN clause
3280 ** and IN_INDEX_NOOP is an allowed reply
3281 ** and the RHS of the IN operator is a list, not a subquery
3282 ** and the RHS is not constant or has two or fewer terms,
3283 ** then it is not worth creating an ephemeral table to evaluate
3284 ** the IN operator so return IN_INDEX_NOOP.
3287 && (inFlags
& IN_INDEX_NOOP_OK
)
3289 && (!sqlite3InRhsIsConstant(pParse
,pX
) || pX
->x
.pList
->nExpr
<=2)
3291 pParse
->nTab
--; /* Back out the allocation of the unused cursor */
3292 iTab
= -1; /* Cursor is not allocated */
3293 eType
= IN_INDEX_NOOP
;
3297 /* Could not find an existing table or index to use as the RHS b-tree.
3298 ** We will have to generate an ephemeral table to do the job.
3300 u32 savedNQueryLoop
= pParse
->nQueryLoop
;
3301 int rMayHaveNull
= 0;
3302 eType
= IN_INDEX_EPH
;
3303 if( inFlags
& IN_INDEX_LOOP
){
3304 pParse
->nQueryLoop
= 0;
3305 }else if( prRhsHasNull
){
3306 *prRhsHasNull
= rMayHaveNull
= ++pParse
->nMem
;
3308 assert( pX
->op
==TK_IN
);
3309 sqlite3CodeRhsOfIN(pParse
, pX
, iTab
);
3311 sqlite3SetHasNullFlag(v
, iTab
, rMayHaveNull
);
3313 pParse
->nQueryLoop
= savedNQueryLoop
;
3316 if( aiMap
&& eType
!=IN_INDEX_INDEX_ASC
&& eType
!=IN_INDEX_INDEX_DESC
){
3318 n
= sqlite3ExprVectorSize(pX
->pLeft
);
3319 for(i
=0; i
<n
; i
++) aiMap
[i
] = i
;
3326 #ifndef SQLITE_OMIT_SUBQUERY
3328 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3329 ** function allocates and returns a nul-terminated string containing
3330 ** the affinities to be used for each column of the comparison.
3332 ** It is the responsibility of the caller to ensure that the returned
3333 ** string is eventually freed using sqlite3DbFree().
3335 static char *exprINAffinity(Parse
*pParse
, const Expr
*pExpr
){
3336 Expr
*pLeft
= pExpr
->pLeft
;
3337 int nVal
= sqlite3ExprVectorSize(pLeft
);
3338 Select
*pSelect
= ExprUseXSelect(pExpr
) ? pExpr
->x
.pSelect
: 0;
3341 assert( pExpr
->op
==TK_IN
);
3342 zRet
= sqlite3DbMallocRaw(pParse
->db
, nVal
+1);
3345 for(i
=0; i
<nVal
; i
++){
3346 Expr
*pA
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3347 char a
= sqlite3ExprAffinity(pA
);
3349 zRet
[i
] = sqlite3CompareAffinity(pSelect
->pEList
->a
[i
].pExpr
, a
);
3360 #ifndef SQLITE_OMIT_SUBQUERY
3362 ** Load the Parse object passed as the first argument with an error
3363 ** message of the form:
3365 ** "sub-select returns N columns - expected M"
3367 void sqlite3SubselectError(Parse
*pParse
, int nActual
, int nExpect
){
3368 if( pParse
->nErr
==0 ){
3369 const char *zFmt
= "sub-select returns %d columns - expected %d";
3370 sqlite3ErrorMsg(pParse
, zFmt
, nActual
, nExpect
);
3376 ** Expression pExpr is a vector that has been used in a context where
3377 ** it is not permitted. If pExpr is a sub-select vector, this routine
3378 ** loads the Parse object with a message of the form:
3380 ** "sub-select returns N columns - expected 1"
3382 ** Or, if it is a regular scalar vector:
3384 ** "row value misused"
3386 void sqlite3VectorErrorMsg(Parse
*pParse
, Expr
*pExpr
){
3387 #ifndef SQLITE_OMIT_SUBQUERY
3388 if( ExprUseXSelect(pExpr
) ){
3389 sqlite3SubselectError(pParse
, pExpr
->x
.pSelect
->pEList
->nExpr
, 1);
3393 sqlite3ErrorMsg(pParse
, "row value misused");
3397 #ifndef SQLITE_OMIT_SUBQUERY
3399 ** Generate code that will construct an ephemeral table containing all terms
3400 ** in the RHS of an IN operator. The IN operator can be in either of two
3403 ** x IN (4,5,11) -- IN operator with list on right-hand side
3404 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3406 ** The pExpr parameter is the IN operator. The cursor number for the
3407 ** constructed ephemeral table is returned. The first time the ephemeral
3408 ** table is computed, the cursor number is also stored in pExpr->iTable,
3409 ** however the cursor number returned might not be the same, as it might
3410 ** have been duplicated using OP_OpenDup.
3412 ** If the LHS expression ("x" in the examples) is a column value, or
3413 ** the SELECT statement returns a column value, then the affinity of that
3414 ** column is used to build the index keys. If both 'x' and the
3415 ** SELECT... statement are columns, then numeric affinity is used
3416 ** if either column has NUMERIC or INTEGER affinity. If neither
3417 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3420 void sqlite3CodeRhsOfIN(
3421 Parse
*pParse
, /* Parsing context */
3422 Expr
*pExpr
, /* The IN operator */
3423 int iTab
/* Use this cursor number */
3425 int addrOnce
= 0; /* Address of the OP_Once instruction at top */
3426 int addr
; /* Address of OP_OpenEphemeral instruction */
3427 Expr
*pLeft
; /* the LHS of the IN operator */
3428 KeyInfo
*pKeyInfo
= 0; /* Key information */
3429 int nVal
; /* Size of vector pLeft */
3430 Vdbe
*v
; /* The prepared statement under construction */
3435 /* The evaluation of the IN must be repeated every time it
3436 ** is encountered if any of the following is true:
3438 ** * The right-hand side is a correlated subquery
3439 ** * The right-hand side is an expression list containing variables
3440 ** * We are inside a trigger
3442 ** If all of the above are false, then we can compute the RHS just once
3443 ** and reuse it many names.
3445 if( !ExprHasProperty(pExpr
, EP_VarSelect
) && pParse
->iSelfTab
==0 ){
3446 /* Reuse of the RHS is allowed */
3447 /* If this routine has already been coded, but the previous code
3448 ** might not have been invoked yet, so invoke it now as a subroutine.
3450 if( ExprHasProperty(pExpr
, EP_Subrtn
) ){
3451 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3452 if( ExprUseXSelect(pExpr
) ){
3453 ExplainQueryPlan((pParse
, 0, "REUSE LIST SUBQUERY %d",
3454 pExpr
->x
.pSelect
->selId
));
3456 assert( ExprUseYSub(pExpr
) );
3457 sqlite3VdbeAddOp2(v
, OP_Gosub
, pExpr
->y
.sub
.regReturn
,
3458 pExpr
->y
.sub
.iAddr
);
3459 assert( iTab
!=pExpr
->iTable
);
3460 sqlite3VdbeAddOp2(v
, OP_OpenDup
, iTab
, pExpr
->iTable
);
3461 sqlite3VdbeJumpHere(v
, addrOnce
);
3465 /* Begin coding the subroutine */
3466 assert( !ExprUseYWin(pExpr
) );
3467 ExprSetProperty(pExpr
, EP_Subrtn
);
3468 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
3469 pExpr
->y
.sub
.regReturn
= ++pParse
->nMem
;
3470 pExpr
->y
.sub
.iAddr
=
3471 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pExpr
->y
.sub
.regReturn
) + 1;
3473 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3476 /* Check to see if this is a vector IN operator */
3477 pLeft
= pExpr
->pLeft
;
3478 nVal
= sqlite3ExprVectorSize(pLeft
);
3480 /* Construct the ephemeral table that will contain the content of
3481 ** RHS of the IN operator.
3483 pExpr
->iTable
= iTab
;
3484 addr
= sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pExpr
->iTable
, nVal
);
3485 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3486 if( ExprUseXSelect(pExpr
) ){
3487 VdbeComment((v
, "Result of SELECT %u", pExpr
->x
.pSelect
->selId
));
3489 VdbeComment((v
, "RHS of IN operator"));
3492 pKeyInfo
= sqlite3KeyInfoAlloc(pParse
->db
, nVal
, 1);
3494 if( ExprUseXSelect(pExpr
) ){
3495 /* Case 1: expr IN (SELECT ...)
3497 ** Generate code to write the results of the select into the temporary
3498 ** table allocated and opened above.
3500 Select
*pSelect
= pExpr
->x
.pSelect
;
3501 ExprList
*pEList
= pSelect
->pEList
;
3503 ExplainQueryPlan((pParse
, 1, "%sLIST SUBQUERY %d",
3504 addrOnce
?"":"CORRELATED ", pSelect
->selId
3506 /* If the LHS and RHS of the IN operator do not match, that
3507 ** error will have been caught long before we reach this point. */
3508 if( ALWAYS(pEList
->nExpr
==nVal
) ){
3513 sqlite3SelectDestInit(&dest
, SRT_Set
, iTab
);
3514 dest
.zAffSdst
= exprINAffinity(pParse
, pExpr
);
3515 pSelect
->iLimit
= 0;
3516 testcase( pSelect
->selFlags
& SF_Distinct
);
3517 testcase( pKeyInfo
==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3518 pCopy
= sqlite3SelectDup(pParse
->db
, pSelect
, 0);
3519 rc
= pParse
->db
->mallocFailed
? 1 :sqlite3Select(pParse
, pCopy
, &dest
);
3520 sqlite3SelectDelete(pParse
->db
, pCopy
);
3521 sqlite3DbFree(pParse
->db
, dest
.zAffSdst
);
3523 sqlite3KeyInfoUnref(pKeyInfo
);
3526 assert( pKeyInfo
!=0 ); /* OOM will cause exit after sqlite3Select() */
3527 assert( pEList
!=0 );
3528 assert( pEList
->nExpr
>0 );
3529 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
3530 for(i
=0; i
<nVal
; i
++){
3531 Expr
*p
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3532 pKeyInfo
->aColl
[i
] = sqlite3BinaryCompareCollSeq(
3533 pParse
, p
, pEList
->a
[i
].pExpr
3537 }else if( ALWAYS(pExpr
->x
.pList
!=0) ){
3538 /* Case 2: expr IN (exprlist)
3540 ** For each expression, build an index key from the evaluation and
3541 ** store it in the temporary table. If <expr> is a column, then use
3542 ** that columns affinity when building index keys. If <expr> is not
3543 ** a column, use numeric affinity.
3545 char affinity
; /* Affinity of the LHS of the IN */
3547 ExprList
*pList
= pExpr
->x
.pList
;
3548 struct ExprList_item
*pItem
;
3550 affinity
= sqlite3ExprAffinity(pLeft
);
3551 if( affinity
<=SQLITE_AFF_NONE
){
3552 affinity
= SQLITE_AFF_BLOB
;
3553 }else if( affinity
==SQLITE_AFF_REAL
){
3554 affinity
= SQLITE_AFF_NUMERIC
;
3557 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
3558 pKeyInfo
->aColl
[0] = sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
3561 /* Loop through each expression in <exprlist>. */
3562 r1
= sqlite3GetTempReg(pParse
);
3563 r2
= sqlite3GetTempReg(pParse
);
3564 for(i
=pList
->nExpr
, pItem
=pList
->a
; i
>0; i
--, pItem
++){
3565 Expr
*pE2
= pItem
->pExpr
;
3567 /* If the expression is not constant then we will need to
3568 ** disable the test that was generated above that makes sure
3569 ** this code only executes once. Because for a non-constant
3570 ** expression we need to rerun this code each time.
3572 if( addrOnce
&& !sqlite3ExprIsConstant(pParse
, pE2
) ){
3573 sqlite3VdbeChangeToNoop(v
, addrOnce
-1);
3574 sqlite3VdbeChangeToNoop(v
, addrOnce
);
3575 ExprClearProperty(pExpr
, EP_Subrtn
);
3579 /* Evaluate the expression and insert it into the temp table */
3580 sqlite3ExprCode(pParse
, pE2
, r1
);
3581 sqlite3VdbeAddOp4(v
, OP_MakeRecord
, r1
, 1, r2
, &affinity
, 1);
3582 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, iTab
, r2
, r1
, 1);
3584 sqlite3ReleaseTempReg(pParse
, r1
);
3585 sqlite3ReleaseTempReg(pParse
, r2
);
3588 sqlite3VdbeChangeP4(v
, addr
, (void *)pKeyInfo
, P4_KEYINFO
);
3591 sqlite3VdbeAddOp1(v
, OP_NullRow
, iTab
);
3592 sqlite3VdbeJumpHere(v
, addrOnce
);
3593 /* Subroutine return */
3594 assert( ExprUseYSub(pExpr
) );
3595 assert( sqlite3VdbeGetOp(v
,pExpr
->y
.sub
.iAddr
-1)->opcode
==OP_BeginSubrtn
3597 sqlite3VdbeAddOp3(v
, OP_Return
, pExpr
->y
.sub
.regReturn
,
3598 pExpr
->y
.sub
.iAddr
, 1);
3600 sqlite3ClearTempRegCache(pParse
);
3603 #endif /* SQLITE_OMIT_SUBQUERY */
3606 ** Generate code for scalar subqueries used as a subquery expression
3607 ** or EXISTS operator:
3609 ** (SELECT a FROM b) -- subquery
3610 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3612 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3614 ** Return the register that holds the result. For a multi-column SELECT,
3615 ** the result is stored in a contiguous array of registers and the
3616 ** return value is the register of the left-most result column.
3617 ** Return 0 if an error occurs.
3619 #ifndef SQLITE_OMIT_SUBQUERY
3620 int sqlite3CodeSubselect(Parse
*pParse
, Expr
*pExpr
){
3621 int addrOnce
= 0; /* Address of OP_Once at top of subroutine */
3622 int rReg
= 0; /* Register storing resulting */
3623 Select
*pSel
; /* SELECT statement to encode */
3624 SelectDest dest
; /* How to deal with SELECT result */
3625 int nReg
; /* Registers to allocate */
3626 Expr
*pLimit
; /* New limit expression */
3627 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3628 int addrExplain
; /* Address of OP_Explain instruction */
3631 Vdbe
*v
= pParse
->pVdbe
;
3633 if( pParse
->nErr
) return 0;
3634 testcase( pExpr
->op
==TK_EXISTS
);
3635 testcase( pExpr
->op
==TK_SELECT
);
3636 assert( pExpr
->op
==TK_EXISTS
|| pExpr
->op
==TK_SELECT
);
3637 assert( ExprUseXSelect(pExpr
) );
3638 pSel
= pExpr
->x
.pSelect
;
3640 /* If this routine has already been coded, then invoke it as a
3642 if( ExprHasProperty(pExpr
, EP_Subrtn
) ){
3643 ExplainQueryPlan((pParse
, 0, "REUSE SUBQUERY %d", pSel
->selId
));
3644 assert( ExprUseYSub(pExpr
) );
3645 sqlite3VdbeAddOp2(v
, OP_Gosub
, pExpr
->y
.sub
.regReturn
,
3646 pExpr
->y
.sub
.iAddr
);
3647 return pExpr
->iTable
;
3650 /* Begin coding the subroutine */
3651 assert( !ExprUseYWin(pExpr
) );
3652 assert( !ExprHasProperty(pExpr
, EP_Reduced
|EP_TokenOnly
) );
3653 ExprSetProperty(pExpr
, EP_Subrtn
);
3654 pExpr
->y
.sub
.regReturn
= ++pParse
->nMem
;
3655 pExpr
->y
.sub
.iAddr
=
3656 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pExpr
->y
.sub
.regReturn
) + 1;
3658 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3659 ** is encountered if any of the following is true:
3661 ** * The right-hand side is a correlated subquery
3662 ** * The right-hand side is an expression list containing variables
3663 ** * We are inside a trigger
3665 ** If all of the above are false, then we can run this code just once
3666 ** save the results, and reuse the same result on subsequent invocations.
3668 if( !ExprHasProperty(pExpr
, EP_VarSelect
) ){
3669 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3672 /* For a SELECT, generate code to put the values for all columns of
3673 ** the first row into an array of registers and return the index of
3674 ** the first register.
3676 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3677 ** into a register and return that register number.
3679 ** In both cases, the query is augmented with "LIMIT 1". Any
3680 ** preexisting limit is discarded in place of the new LIMIT 1.
3682 ExplainQueryPlan2(addrExplain
, (pParse
, 1, "%sSCALAR SUBQUERY %d",
3683 addrOnce
?"":"CORRELATED ", pSel
->selId
));
3684 sqlite3VdbeScanStatusCounters(v
, addrExplain
, addrExplain
, -1);
3685 nReg
= pExpr
->op
==TK_SELECT
? pSel
->pEList
->nExpr
: 1;
3686 sqlite3SelectDestInit(&dest
, 0, pParse
->nMem
+1);
3687 pParse
->nMem
+= nReg
;
3688 if( pExpr
->op
==TK_SELECT
){
3689 dest
.eDest
= SRT_Mem
;
3690 dest
.iSdst
= dest
.iSDParm
;
3692 sqlite3VdbeAddOp3(v
, OP_Null
, 0, dest
.iSDParm
, dest
.iSDParm
+nReg
-1);
3693 VdbeComment((v
, "Init subquery result"));
3695 dest
.eDest
= SRT_Exists
;
3696 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
.iSDParm
);
3697 VdbeComment((v
, "Init EXISTS result"));
3700 /* The subquery already has a limit. If the pre-existing limit is X
3701 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3702 sqlite3
*db
= pParse
->db
;
3703 pLimit
= sqlite3Expr(db
, TK_INTEGER
, "0");
3705 pLimit
->affExpr
= SQLITE_AFF_NUMERIC
;
3706 pLimit
= sqlite3PExpr(pParse
, TK_NE
,
3707 sqlite3ExprDup(db
, pSel
->pLimit
->pLeft
, 0), pLimit
);
3709 sqlite3ExprDeferredDelete(pParse
, pSel
->pLimit
->pLeft
);
3710 pSel
->pLimit
->pLeft
= pLimit
;
3712 /* If there is no pre-existing limit add a limit of 1 */
3713 pLimit
= sqlite3Expr(pParse
->db
, TK_INTEGER
, "1");
3714 pSel
->pLimit
= sqlite3PExpr(pParse
, TK_LIMIT
, pLimit
, 0);
3717 if( sqlite3Select(pParse
, pSel
, &dest
) ){
3718 pExpr
->op2
= pExpr
->op
;
3719 pExpr
->op
= TK_ERROR
;
3722 pExpr
->iTable
= rReg
= dest
.iSDParm
;
3723 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
3725 sqlite3VdbeJumpHere(v
, addrOnce
);
3727 sqlite3VdbeScanStatusRange(v
, addrExplain
, addrExplain
, -1);
3729 /* Subroutine return */
3730 assert( ExprUseYSub(pExpr
) );
3731 assert( sqlite3VdbeGetOp(v
,pExpr
->y
.sub
.iAddr
-1)->opcode
==OP_BeginSubrtn
3733 sqlite3VdbeAddOp3(v
, OP_Return
, pExpr
->y
.sub
.regReturn
,
3734 pExpr
->y
.sub
.iAddr
, 1);
3736 sqlite3ClearTempRegCache(pParse
);
3739 #endif /* SQLITE_OMIT_SUBQUERY */
3741 #ifndef SQLITE_OMIT_SUBQUERY
3743 ** Expr pIn is an IN(...) expression. This function checks that the
3744 ** sub-select on the RHS of the IN() operator has the same number of
3745 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3746 ** a sub-query, that the LHS is a vector of size 1.
3748 int sqlite3ExprCheckIN(Parse
*pParse
, Expr
*pIn
){
3749 int nVector
= sqlite3ExprVectorSize(pIn
->pLeft
);
3750 if( ExprUseXSelect(pIn
) && !pParse
->db
->mallocFailed
){
3751 if( nVector
!=pIn
->x
.pSelect
->pEList
->nExpr
){
3752 sqlite3SubselectError(pParse
, pIn
->x
.pSelect
->pEList
->nExpr
, nVector
);
3755 }else if( nVector
!=1 ){
3756 sqlite3VectorErrorMsg(pParse
, pIn
->pLeft
);
3763 #ifndef SQLITE_OMIT_SUBQUERY
3765 ** Generate code for an IN expression.
3767 ** x IN (SELECT ...)
3768 ** x IN (value, value, ...)
3770 ** The left-hand side (LHS) is a scalar or vector expression. The
3771 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3772 ** subquery. If the RHS is a subquery, the number of result columns must
3773 ** match the number of columns in the vector on the LHS. If the RHS is
3774 ** a list of values, the LHS must be a scalar.
3776 ** The IN operator is true if the LHS value is contained within the RHS.
3777 ** The result is false if the LHS is definitely not in the RHS. The
3778 ** result is NULL if the presence of the LHS in the RHS cannot be
3779 ** determined due to NULLs.
3781 ** This routine generates code that jumps to destIfFalse if the LHS is not
3782 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3783 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3784 ** within the RHS then fall through.
3786 ** See the separate in-operator.md documentation file in the canonical
3787 ** SQLite source tree for additional information.
3789 static void sqlite3ExprCodeIN(
3790 Parse
*pParse
, /* Parsing and code generating context */
3791 Expr
*pExpr
, /* The IN expression */
3792 int destIfFalse
, /* Jump here if LHS is not contained in the RHS */
3793 int destIfNull
/* Jump here if the results are unknown due to NULLs */
3795 int rRhsHasNull
= 0; /* Register that is true if RHS contains NULL values */
3796 int eType
; /* Type of the RHS */
3797 int rLhs
; /* Register(s) holding the LHS values */
3798 int rLhsOrig
; /* LHS values prior to reordering by aiMap[] */
3799 Vdbe
*v
; /* Statement under construction */
3800 int *aiMap
= 0; /* Map from vector field to index column */
3801 char *zAff
= 0; /* Affinity string for comparisons */
3802 int nVector
; /* Size of vectors for this IN operator */
3803 int iDummy
; /* Dummy parameter to exprCodeVector() */
3804 Expr
*pLeft
; /* The LHS of the IN operator */
3805 int i
; /* loop counter */
3806 int destStep2
; /* Where to jump when NULLs seen in step 2 */
3807 int destStep6
= 0; /* Start of code for Step 6 */
3808 int addrTruthOp
; /* Address of opcode that determines the IN is true */
3809 int destNotNull
; /* Jump here if a comparison is not true in step 6 */
3810 int addrTop
; /* Top of the step-6 loop */
3811 int iTab
= 0; /* Index to use */
3812 u8 okConstFactor
= pParse
->okConstFactor
;
3814 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
3815 pLeft
= pExpr
->pLeft
;
3816 if( sqlite3ExprCheckIN(pParse
, pExpr
) ) return;
3817 zAff
= exprINAffinity(pParse
, pExpr
);
3818 nVector
= sqlite3ExprVectorSize(pExpr
->pLeft
);
3819 aiMap
= (int*)sqlite3DbMallocZero(
3820 pParse
->db
, nVector
*(sizeof(int) + sizeof(char)) + 1
3822 if( pParse
->db
->mallocFailed
) goto sqlite3ExprCodeIN_oom_error
;
3824 /* Attempt to compute the RHS. After this step, if anything other than
3825 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3826 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3827 ** the RHS has not yet been coded. */
3829 assert( v
!=0 ); /* OOM detected prior to this routine */
3830 VdbeNoopComment((v
, "begin IN expr"));
3831 eType
= sqlite3FindInIndex(pParse
, pExpr
,
3832 IN_INDEX_MEMBERSHIP
| IN_INDEX_NOOP_OK
,
3833 destIfFalse
==destIfNull
? 0 : &rRhsHasNull
,
3836 assert( pParse
->nErr
|| nVector
==1 || eType
==IN_INDEX_EPH
3837 || eType
==IN_INDEX_INDEX_ASC
|| eType
==IN_INDEX_INDEX_DESC
3840 /* Confirm that aiMap[] contains nVector integer values between 0 and
3842 for(i
=0; i
<nVector
; i
++){
3844 for(cnt
=j
=0; j
<nVector
; j
++) if( aiMap
[j
]==i
) cnt
++;
3849 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3850 ** vector, then it is stored in an array of nVector registers starting
3853 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3854 ** so that the fields are in the same order as an existing index. The
3855 ** aiMap[] array contains a mapping from the original LHS field order to
3856 ** the field order that matches the RHS index.
3858 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3859 ** even if it is constant, as OP_Affinity may be used on the register
3860 ** by code generated below. */
3861 assert( pParse
->okConstFactor
==okConstFactor
);
3862 pParse
->okConstFactor
= 0;
3863 rLhsOrig
= exprCodeVector(pParse
, pLeft
, &iDummy
);
3864 pParse
->okConstFactor
= okConstFactor
;
3865 for(i
=0; i
<nVector
&& aiMap
[i
]==i
; i
++){} /* Are LHS fields reordered? */
3867 /* LHS fields are not reordered */
3870 /* Need to reorder the LHS fields according to aiMap */
3871 rLhs
= sqlite3GetTempRange(pParse
, nVector
);
3872 for(i
=0; i
<nVector
; i
++){
3873 sqlite3VdbeAddOp3(v
, OP_Copy
, rLhsOrig
+i
, rLhs
+aiMap
[i
], 0);
3877 /* If sqlite3FindInIndex() did not find or create an index that is
3878 ** suitable for evaluating the IN operator, then evaluate using a
3879 ** sequence of comparisons.
3881 ** This is step (1) in the in-operator.md optimized algorithm.
3883 if( eType
==IN_INDEX_NOOP
){
3886 int labelOk
= sqlite3VdbeMakeLabel(pParse
);
3890 assert( ExprUseXList(pExpr
) );
3891 pList
= pExpr
->x
.pList
;
3892 pColl
= sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
3893 if( destIfNull
!=destIfFalse
){
3894 regCkNull
= sqlite3GetTempReg(pParse
);
3895 sqlite3VdbeAddOp3(v
, OP_BitAnd
, rLhs
, rLhs
, regCkNull
);
3897 for(ii
=0; ii
<pList
->nExpr
; ii
++){
3898 r2
= sqlite3ExprCodeTemp(pParse
, pList
->a
[ii
].pExpr
, ®ToFree
);
3899 if( regCkNull
&& sqlite3ExprCanBeNull(pList
->a
[ii
].pExpr
) ){
3900 sqlite3VdbeAddOp3(v
, OP_BitAnd
, regCkNull
, r2
, regCkNull
);
3902 sqlite3ReleaseTempReg(pParse
, regToFree
);
3903 if( ii
<pList
->nExpr
-1 || destIfNull
!=destIfFalse
){
3904 int op
= rLhs
!=r2
? OP_Eq
: OP_NotNull
;
3905 sqlite3VdbeAddOp4(v
, op
, rLhs
, labelOk
, r2
,
3906 (void*)pColl
, P4_COLLSEQ
);
3907 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1 && op
==OP_Eq
);
3908 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1 && op
==OP_Eq
);
3909 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1 && op
==OP_NotNull
);
3910 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1 && op
==OP_NotNull
);
3911 sqlite3VdbeChangeP5(v
, zAff
[0]);
3913 int op
= rLhs
!=r2
? OP_Ne
: OP_IsNull
;
3914 assert( destIfNull
==destIfFalse
);
3915 sqlite3VdbeAddOp4(v
, op
, rLhs
, destIfFalse
, r2
,
3916 (void*)pColl
, P4_COLLSEQ
);
3917 VdbeCoverageIf(v
, op
==OP_Ne
);
3918 VdbeCoverageIf(v
, op
==OP_IsNull
);
3919 sqlite3VdbeChangeP5(v
, zAff
[0] | SQLITE_JUMPIFNULL
);
3923 sqlite3VdbeAddOp2(v
, OP_IsNull
, regCkNull
, destIfNull
); VdbeCoverage(v
);
3924 sqlite3VdbeGoto(v
, destIfFalse
);
3926 sqlite3VdbeResolveLabel(v
, labelOk
);
3927 sqlite3ReleaseTempReg(pParse
, regCkNull
);
3928 goto sqlite3ExprCodeIN_finished
;
3931 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3932 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3933 ** We will then skip the binary search of the RHS.
3935 if( destIfNull
==destIfFalse
){
3936 destStep2
= destIfFalse
;
3938 destStep2
= destStep6
= sqlite3VdbeMakeLabel(pParse
);
3940 for(i
=0; i
<nVector
; i
++){
3941 Expr
*p
= sqlite3VectorFieldSubexpr(pExpr
->pLeft
, i
);
3942 if( pParse
->nErr
) goto sqlite3ExprCodeIN_oom_error
;
3943 if( sqlite3ExprCanBeNull(p
) ){
3944 sqlite3VdbeAddOp2(v
, OP_IsNull
, rLhs
+i
, destStep2
);
3949 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3950 ** of the RHS using the LHS as a probe. If found, the result is
3953 if( eType
==IN_INDEX_ROWID
){
3954 /* In this case, the RHS is the ROWID of table b-tree and so we also
3955 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3956 ** into a single opcode. */
3957 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, iTab
, destIfFalse
, rLhs
);
3959 addrTruthOp
= sqlite3VdbeAddOp0(v
, OP_Goto
); /* Return True */
3961 sqlite3VdbeAddOp4(v
, OP_Affinity
, rLhs
, nVector
, 0, zAff
, nVector
);
3962 if( destIfFalse
==destIfNull
){
3963 /* Combine Step 3 and Step 5 into a single opcode */
3964 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, iTab
, destIfFalse
,
3965 rLhs
, nVector
); VdbeCoverage(v
);
3966 goto sqlite3ExprCodeIN_finished
;
3968 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3969 addrTruthOp
= sqlite3VdbeAddOp4Int(v
, OP_Found
, iTab
, 0,
3970 rLhs
, nVector
); VdbeCoverage(v
);
3973 /* Step 4. If the RHS is known to be non-NULL and we did not find
3974 ** an match on the search above, then the result must be FALSE.
3976 if( rRhsHasNull
&& nVector
==1 ){
3977 sqlite3VdbeAddOp2(v
, OP_NotNull
, rRhsHasNull
, destIfFalse
);
3981 /* Step 5. If we do not care about the difference between NULL and
3982 ** FALSE, then just return false.
3984 if( destIfFalse
==destIfNull
) sqlite3VdbeGoto(v
, destIfFalse
);
3986 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3987 ** If any comparison is NULL, then the result is NULL. If all
3988 ** comparisons are FALSE then the final result is FALSE.
3990 ** For a scalar LHS, it is sufficient to check just the first row
3993 if( destStep6
) sqlite3VdbeResolveLabel(v
, destStep6
);
3994 addrTop
= sqlite3VdbeAddOp2(v
, OP_Rewind
, iTab
, destIfFalse
);
3997 destNotNull
= sqlite3VdbeMakeLabel(pParse
);
3999 /* For nVector==1, combine steps 6 and 7 by immediately returning
4000 ** FALSE if the first comparison is not NULL */
4001 destNotNull
= destIfFalse
;
4003 for(i
=0; i
<nVector
; i
++){
4006 int r3
= sqlite3GetTempReg(pParse
);
4007 p
= sqlite3VectorFieldSubexpr(pLeft
, i
);
4008 pColl
= sqlite3ExprCollSeq(pParse
, p
);
4009 sqlite3VdbeAddOp3(v
, OP_Column
, iTab
, i
, r3
);
4010 sqlite3VdbeAddOp4(v
, OP_Ne
, rLhs
+i
, destNotNull
, r3
,
4011 (void*)pColl
, P4_COLLSEQ
);
4013 sqlite3ReleaseTempReg(pParse
, r3
);
4015 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfNull
);
4017 sqlite3VdbeResolveLabel(v
, destNotNull
);
4018 sqlite3VdbeAddOp2(v
, OP_Next
, iTab
, addrTop
+1);
4021 /* Step 7: If we reach this point, we know that the result must
4023 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfFalse
);
4026 /* Jumps here in order to return true. */
4027 sqlite3VdbeJumpHere(v
, addrTruthOp
);
4029 sqlite3ExprCodeIN_finished
:
4030 if( rLhs
!=rLhsOrig
) sqlite3ReleaseTempReg(pParse
, rLhs
);
4031 VdbeComment((v
, "end IN expr"));
4032 sqlite3ExprCodeIN_oom_error
:
4033 sqlite3DbFree(pParse
->db
, aiMap
);
4034 sqlite3DbFree(pParse
->db
, zAff
);
4036 #endif /* SQLITE_OMIT_SUBQUERY */
4038 #ifndef SQLITE_OMIT_FLOATING_POINT
4040 ** Generate an instruction that will put the floating point
4041 ** value described by z[0..n-1] into register iMem.
4043 ** The z[] string will probably not be zero-terminated. But the
4044 ** z[n] character is guaranteed to be something that does not look
4045 ** like the continuation of the number.
4047 static void codeReal(Vdbe
*v
, const char *z
, int negateFlag
, int iMem
){
4050 sqlite3AtoF(z
, &value
, sqlite3Strlen30(z
), SQLITE_UTF8
);
4051 assert( !sqlite3IsNaN(value
) ); /* The new AtoF never returns NaN */
4052 if( negateFlag
) value
= -value
;
4053 sqlite3VdbeAddOp4Dup8(v
, OP_Real
, 0, iMem
, 0, (u8
*)&value
, P4_REAL
);
4060 ** Generate an instruction that will put the integer describe by
4061 ** text z[0..n-1] into register iMem.
4063 ** Expr.u.zToken is always UTF8 and zero-terminated.
4065 static void codeInteger(Parse
*pParse
, Expr
*pExpr
, int negFlag
, int iMem
){
4066 Vdbe
*v
= pParse
->pVdbe
;
4067 if( pExpr
->flags
& EP_IntValue
){
4068 int i
= pExpr
->u
.iValue
;
4070 if( negFlag
) i
= -i
;
4071 sqlite3VdbeAddOp2(v
, OP_Integer
, i
, iMem
);
4075 const char *z
= pExpr
->u
.zToken
;
4077 c
= sqlite3DecOrHexToI64(z
, &value
);
4078 if( (c
==3 && !negFlag
) || (c
==2) || (negFlag
&& value
==SMALLEST_INT64
)){
4079 #ifdef SQLITE_OMIT_FLOATING_POINT
4080 sqlite3ErrorMsg(pParse
, "oversized integer: %s%#T", negFlag
?"-":"",pExpr
);
4082 #ifndef SQLITE_OMIT_HEX_INTEGER
4083 if( sqlite3_strnicmp(z
,"0x",2)==0 ){
4084 sqlite3ErrorMsg(pParse
, "hex literal too big: %s%#T",
4085 negFlag
?"-":"",pExpr
);
4089 codeReal(v
, z
, negFlag
, iMem
);
4093 if( negFlag
){ value
= c
==3 ? SMALLEST_INT64
: -value
; }
4094 sqlite3VdbeAddOp4Dup8(v
, OP_Int64
, 0, iMem
, 0, (u8
*)&value
, P4_INT64
);
4100 /* Generate code that will load into register regOut a value that is
4101 ** appropriate for the iIdxCol-th column of index pIdx.
4103 void sqlite3ExprCodeLoadIndexColumn(
4104 Parse
*pParse
, /* The parsing context */
4105 Index
*pIdx
, /* The index whose column is to be loaded */
4106 int iTabCur
, /* Cursor pointing to a table row */
4107 int iIdxCol
, /* The column of the index to be loaded */
4108 int regOut
/* Store the index column value in this register */
4110 i16 iTabCol
= pIdx
->aiColumn
[iIdxCol
];
4111 if( iTabCol
==XN_EXPR
){
4112 assert( pIdx
->aColExpr
);
4113 assert( pIdx
->aColExpr
->nExpr
>iIdxCol
);
4114 pParse
->iSelfTab
= iTabCur
+ 1;
4115 sqlite3ExprCodeCopy(pParse
, pIdx
->aColExpr
->a
[iIdxCol
].pExpr
, regOut
);
4116 pParse
->iSelfTab
= 0;
4118 sqlite3ExprCodeGetColumnOfTable(pParse
->pVdbe
, pIdx
->pTable
, iTabCur
,
4123 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4125 ** Generate code that will compute the value of generated column pCol
4126 ** and store the result in register regOut
4128 void sqlite3ExprCodeGeneratedColumn(
4129 Parse
*pParse
, /* Parsing context */
4130 Table
*pTab
, /* Table containing the generated column */
4131 Column
*pCol
, /* The generated column */
4132 int regOut
/* Put the result in this register */
4135 Vdbe
*v
= pParse
->pVdbe
;
4136 int nErr
= pParse
->nErr
;
4138 assert( pParse
->iSelfTab
!=0 );
4139 if( pParse
->iSelfTab
>0 ){
4140 iAddr
= sqlite3VdbeAddOp3(v
, OP_IfNullRow
, pParse
->iSelfTab
-1, 0, regOut
);
4144 sqlite3ExprCodeCopy(pParse
, sqlite3ColumnExpr(pTab
,pCol
), regOut
);
4145 if( pCol
->affinity
>=SQLITE_AFF_TEXT
){
4146 sqlite3VdbeAddOp4(v
, OP_Affinity
, regOut
, 1, 0, &pCol
->affinity
, 1);
4148 if( iAddr
) sqlite3VdbeJumpHere(v
, iAddr
);
4149 if( pParse
->nErr
>nErr
) pParse
->db
->errByteOffset
= -1;
4151 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4154 ** Generate code to extract the value of the iCol-th column of a table.
4156 void sqlite3ExprCodeGetColumnOfTable(
4157 Vdbe
*v
, /* Parsing context */
4158 Table
*pTab
, /* The table containing the value */
4159 int iTabCur
, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
4160 int iCol
, /* Index of the column to extract */
4161 int regOut
/* Extract the value into this register */
4166 assert( iCol
!=XN_EXPR
);
4167 if( iCol
<0 || iCol
==pTab
->iPKey
){
4168 sqlite3VdbeAddOp2(v
, OP_Rowid
, iTabCur
, regOut
);
4169 VdbeComment((v
, "%s.rowid", pTab
->zName
));
4173 if( IsVirtual(pTab
) ){
4176 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4177 }else if( (pCol
= &pTab
->aCol
[iCol
])->colFlags
& COLFLAG_VIRTUAL
){
4178 Parse
*pParse
= sqlite3VdbeParser(v
);
4179 if( pCol
->colFlags
& COLFLAG_BUSY
){
4180 sqlite3ErrorMsg(pParse
, "generated column loop on \"%s\"",
4183 int savedSelfTab
= pParse
->iSelfTab
;
4184 pCol
->colFlags
|= COLFLAG_BUSY
;
4185 pParse
->iSelfTab
= iTabCur
+1;
4186 sqlite3ExprCodeGeneratedColumn(pParse
, pTab
, pCol
, regOut
);
4187 pParse
->iSelfTab
= savedSelfTab
;
4188 pCol
->colFlags
&= ~COLFLAG_BUSY
;
4192 }else if( !HasRowid(pTab
) ){
4193 testcase( iCol
!=sqlite3TableColumnToStorage(pTab
, iCol
) );
4194 x
= sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab
), iCol
);
4197 x
= sqlite3TableColumnToStorage(pTab
,iCol
);
4198 testcase( x
!=iCol
);
4201 sqlite3VdbeAddOp3(v
, op
, iTabCur
, x
, regOut
);
4202 sqlite3ColumnDefault(v
, pTab
, iCol
, regOut
);
4207 ** Generate code that will extract the iColumn-th column from
4208 ** table pTab and store the column value in register iReg.
4210 ** There must be an open cursor to pTab in iTable when this routine
4211 ** is called. If iColumn<0 then code is generated that extracts the rowid.
4213 int sqlite3ExprCodeGetColumn(
4214 Parse
*pParse
, /* Parsing and code generating context */
4215 Table
*pTab
, /* Description of the table we are reading from */
4216 int iColumn
, /* Index of the table column */
4217 int iTable
, /* The cursor pointing to the table */
4218 int iReg
, /* Store results here */
4219 u8 p5
/* P5 value for OP_Column + FLAGS */
4221 assert( pParse
->pVdbe
!=0 );
4222 assert( (p5
& (OPFLAG_NOCHNG
|OPFLAG_TYPEOFARG
|OPFLAG_LENGTHARG
))==p5
);
4223 assert( IsVirtual(pTab
) || (p5
& OPFLAG_NOCHNG
)==0 );
4224 sqlite3ExprCodeGetColumnOfTable(pParse
->pVdbe
, pTab
, iTable
, iColumn
, iReg
);
4226 VdbeOp
*pOp
= sqlite3VdbeGetLastOp(pParse
->pVdbe
);
4227 if( pOp
->opcode
==OP_Column
) pOp
->p5
= p5
;
4228 if( pOp
->opcode
==OP_VColumn
) pOp
->p5
= (p5
& OPFLAG_NOCHNG
);
4234 ** Generate code to move content from registers iFrom...iFrom+nReg-1
4235 ** over to iTo..iTo+nReg-1.
4237 void sqlite3ExprCodeMove(Parse
*pParse
, int iFrom
, int iTo
, int nReg
){
4238 sqlite3VdbeAddOp3(pParse
->pVdbe
, OP_Move
, iFrom
, iTo
, nReg
);
4242 ** Convert a scalar expression node to a TK_REGISTER referencing
4243 ** register iReg. The caller must ensure that iReg already contains
4244 ** the correct value for the expression.
4246 static void exprToRegister(Expr
*pExpr
, int iReg
){
4247 Expr
*p
= sqlite3ExprSkipCollateAndLikely(pExpr
);
4248 if( NEVER(p
==0) ) return;
4250 p
->op
= TK_REGISTER
;
4252 ExprClearProperty(p
, EP_Skip
);
4256 ** Evaluate an expression (either a vector or a scalar expression) and store
4257 ** the result in contiguous temporary registers. Return the index of
4258 ** the first register used to store the result.
4260 ** If the returned result register is a temporary scalar, then also write
4261 ** that register number into *piFreeable. If the returned result register
4262 ** is not a temporary or if the expression is a vector set *piFreeable
4265 static int exprCodeVector(Parse
*pParse
, Expr
*p
, int *piFreeable
){
4267 int nResult
= sqlite3ExprVectorSize(p
);
4269 iResult
= sqlite3ExprCodeTemp(pParse
, p
, piFreeable
);
4272 if( p
->op
==TK_SELECT
){
4273 #if SQLITE_OMIT_SUBQUERY
4276 iResult
= sqlite3CodeSubselect(pParse
, p
);
4280 iResult
= pParse
->nMem
+1;
4281 pParse
->nMem
+= nResult
;
4282 assert( ExprUseXList(p
) );
4283 for(i
=0; i
<nResult
; i
++){
4284 sqlite3ExprCodeFactorable(pParse
, p
->x
.pList
->a
[i
].pExpr
, i
+iResult
);
4292 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
4293 ** so that a subsequent copy will not be merged into this one.
4295 static void setDoNotMergeFlagOnCopy(Vdbe
*v
){
4296 if( sqlite3VdbeGetLastOp(v
)->opcode
==OP_Copy
){
4297 sqlite3VdbeChangeP5(v
, 1); /* Tag trailing OP_Copy as not mergeable */
4302 ** Generate code to implement special SQL functions that are implemented
4303 ** in-line rather than by using the usual callbacks.
4305 static int exprCodeInlineFunction(
4306 Parse
*pParse
, /* Parsing context */
4307 ExprList
*pFarg
, /* List of function arguments */
4308 int iFuncId
, /* Function ID. One of the INTFUNC_... values */
4309 int target
/* Store function result in this register */
4312 Vdbe
*v
= pParse
->pVdbe
;
4315 nFarg
= pFarg
->nExpr
;
4316 assert( nFarg
>0 ); /* All in-line functions have at least one argument */
4318 case INLINEFUNC_coalesce
: {
4319 /* Attempt a direct implementation of the built-in COALESCE() and
4320 ** IFNULL() functions. This avoids unnecessary evaluation of
4321 ** arguments past the first non-NULL argument.
4323 int endCoalesce
= sqlite3VdbeMakeLabel(pParse
);
4326 sqlite3ExprCode(pParse
, pFarg
->a
[0].pExpr
, target
);
4327 for(i
=1; i
<nFarg
; i
++){
4328 sqlite3VdbeAddOp2(v
, OP_NotNull
, target
, endCoalesce
);
4330 sqlite3ExprCode(pParse
, pFarg
->a
[i
].pExpr
, target
);
4332 setDoNotMergeFlagOnCopy(v
);
4333 sqlite3VdbeResolveLabel(v
, endCoalesce
);
4336 case INLINEFUNC_iif
: {
4338 memset(&caseExpr
, 0, sizeof(caseExpr
));
4339 caseExpr
.op
= TK_CASE
;
4340 caseExpr
.x
.pList
= pFarg
;
4341 return sqlite3ExprCodeTarget(pParse
, &caseExpr
, target
);
4343 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4344 case INLINEFUNC_sqlite_offset
: {
4345 Expr
*pArg
= pFarg
->a
[0].pExpr
;
4346 if( pArg
->op
==TK_COLUMN
&& pArg
->iTable
>=0 ){
4347 sqlite3VdbeAddOp3(v
, OP_Offset
, pArg
->iTable
, pArg
->iColumn
, target
);
4349 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4355 /* The UNLIKELY() function is a no-op. The result is the value
4356 ** of the first argument.
4358 assert( nFarg
==1 || nFarg
==2 );
4359 target
= sqlite3ExprCodeTarget(pParse
, pFarg
->a
[0].pExpr
, target
);
4363 /***********************************************************************
4364 ** Test-only SQL functions that are only usable if enabled
4365 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4367 #if !defined(SQLITE_UNTESTABLE)
4368 case INLINEFUNC_expr_compare
: {
4369 /* Compare two expressions using sqlite3ExprCompare() */
4371 sqlite3VdbeAddOp2(v
, OP_Integer
,
4372 sqlite3ExprCompare(0,pFarg
->a
[0].pExpr
, pFarg
->a
[1].pExpr
,-1),
4377 case INLINEFUNC_expr_implies_expr
: {
4378 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4380 sqlite3VdbeAddOp2(v
, OP_Integer
,
4381 sqlite3ExprImpliesExpr(pParse
,pFarg
->a
[0].pExpr
, pFarg
->a
[1].pExpr
,-1),
4386 case INLINEFUNC_implies_nonnull_row
: {
4387 /* Result of sqlite3ExprImpliesNonNullRow() */
4390 pA1
= pFarg
->a
[1].pExpr
;
4391 if( pA1
->op
==TK_COLUMN
){
4392 sqlite3VdbeAddOp2(v
, OP_Integer
,
4393 sqlite3ExprImpliesNonNullRow(pFarg
->a
[0].pExpr
,pA1
->iTable
,1),
4396 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4401 case INLINEFUNC_affinity
: {
4402 /* The AFFINITY() function evaluates to a string that describes
4403 ** the type affinity of the argument. This is used for testing of
4404 ** the SQLite type logic.
4406 const char *azAff
[] = { "blob", "text", "numeric", "integer",
4407 "real", "flexnum" };
4410 aff
= sqlite3ExprAffinity(pFarg
->a
[0].pExpr
);
4411 assert( aff
<=SQLITE_AFF_NONE
4412 || (aff
>=SQLITE_AFF_BLOB
&& aff
<=SQLITE_AFF_FLEXNUM
) );
4413 sqlite3VdbeLoadString(v
, target
,
4414 (aff
<=SQLITE_AFF_NONE
) ? "none" : azAff
[aff
-SQLITE_AFF_BLOB
]);
4417 #endif /* !defined(SQLITE_UNTESTABLE) */
4423 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4424 ** If it is, then resolve the expression by reading from the index and
4425 ** return the register into which the value has been read. If pExpr is
4426 ** not an indexed expression, then return negative.
4428 static SQLITE_NOINLINE
int sqlite3IndexedExprLookup(
4429 Parse
*pParse
, /* The parsing context */
4430 Expr
*pExpr
, /* The expression to potentially bypass */
4431 int target
/* Where to store the result of the expression */
4435 for(p
=pParse
->pIdxEpr
; p
; p
=p
->pIENext
){
4437 int iDataCur
= p
->iDataCur
;
4438 if( iDataCur
<0 ) continue;
4439 if( pParse
->iSelfTab
){
4440 if( p
->iDataCur
!=pParse
->iSelfTab
-1 ) continue;
4443 if( sqlite3ExprCompare(0, pExpr
, p
->pExpr
, iDataCur
)!=0 ) continue;
4444 assert( p
->aff
>=SQLITE_AFF_BLOB
&& p
->aff
<=SQLITE_AFF_NUMERIC
);
4445 exprAff
= sqlite3ExprAffinity(pExpr
);
4446 if( (exprAff
<=SQLITE_AFF_BLOB
&& p
->aff
!=SQLITE_AFF_BLOB
)
4447 || (exprAff
==SQLITE_AFF_TEXT
&& p
->aff
!=SQLITE_AFF_TEXT
)
4448 || (exprAff
>=SQLITE_AFF_NUMERIC
&& p
->aff
!=SQLITE_AFF_NUMERIC
)
4450 /* Affinity mismatch on a generated column */
4456 if( p
->bMaybeNullRow
){
4457 /* If the index is on a NULL row due to an outer join, then we
4458 ** cannot extract the value from the index. The value must be
4459 ** computed using the original expression. */
4460 int addr
= sqlite3VdbeCurrentAddr(v
);
4461 sqlite3VdbeAddOp3(v
, OP_IfNullRow
, p
->iIdxCur
, addr
+3, target
);
4463 sqlite3VdbeAddOp3(v
, OP_Column
, p
->iIdxCur
, p
->iIdxCol
, target
);
4464 VdbeComment((v
, "%s expr-column %d", p
->zIdxName
, p
->iIdxCol
));
4465 sqlite3VdbeGoto(v
, 0);
4466 p
= pParse
->pIdxEpr
;
4467 pParse
->pIdxEpr
= 0;
4468 sqlite3ExprCode(pParse
, pExpr
, target
);
4469 pParse
->pIdxEpr
= p
;
4470 sqlite3VdbeJumpHere(v
, addr
+2);
4472 sqlite3VdbeAddOp3(v
, OP_Column
, p
->iIdxCur
, p
->iIdxCol
, target
);
4473 VdbeComment((v
, "%s expr-column %d", p
->zIdxName
, p
->iIdxCol
));
4477 return -1; /* Not found */
4482 ** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This
4483 ** function checks the Parse.pIdxPartExpr list to see if this column
4484 ** can be replaced with a constant value. If so, it generates code to
4485 ** put the constant value in a register (ideally, but not necessarily,
4486 ** register iTarget) and returns the register number.
4488 ** Or, if the TK_COLUMN cannot be replaced by a constant, zero is
4491 static int exprPartidxExprLookup(Parse
*pParse
, Expr
*pExpr
, int iTarget
){
4493 for(p
=pParse
->pIdxPartExpr
; p
; p
=p
->pIENext
){
4494 if( pExpr
->iColumn
==p
->iIdxCol
&& pExpr
->iTable
==p
->iDataCur
){
4495 Vdbe
*v
= pParse
->pVdbe
;
4499 if( p
->bMaybeNullRow
){
4500 addr
= sqlite3VdbeAddOp1(v
, OP_IfNullRow
, p
->iIdxCur
);
4502 ret
= sqlite3ExprCodeTarget(pParse
, p
->pExpr
, iTarget
);
4503 sqlite3VdbeAddOp4(pParse
->pVdbe
, OP_Affinity
, ret
, 1, 0,
4504 (const char*)&p
->aff
, 1);
4506 sqlite3VdbeJumpHere(v
, addr
);
4507 sqlite3VdbeChangeP3(v
, addr
, ret
);
4517 ** Generate code into the current Vdbe to evaluate the given
4518 ** expression. Attempt to store the results in register "target".
4519 ** Return the register where results are stored.
4521 ** With this routine, there is no guarantee that results will
4522 ** be stored in target. The result might be stored in some other
4523 ** register if it is convenient to do so. The calling function
4524 ** must check the return code and move the results to the desired
4527 int sqlite3ExprCodeTarget(Parse
*pParse
, Expr
*pExpr
, int target
){
4528 Vdbe
*v
= pParse
->pVdbe
; /* The VM under construction */
4529 int op
; /* The opcode being coded */
4530 int inReg
= target
; /* Results stored in register inReg */
4531 int regFree1
= 0; /* If non-zero free this temporary register */
4532 int regFree2
= 0; /* If non-zero free this temporary register */
4533 int r1
, r2
; /* Various register numbers */
4534 Expr tempX
; /* Temporary expression node */
4537 assert( target
>0 && target
<=pParse
->nMem
);
4543 }else if( pParse
->pIdxEpr
!=0
4544 && !ExprHasProperty(pExpr
, EP_Leaf
)
4545 && (r1
= sqlite3IndexedExprLookup(pParse
, pExpr
, target
))>=0
4549 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
4552 assert( op
!=TK_ORDER
);
4554 case TK_AGG_COLUMN
: {
4555 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
4556 struct AggInfo_col
*pCol
;
4557 assert( pAggInfo
!=0 );
4558 assert( pExpr
->iAgg
>=0 );
4559 if( pExpr
->iAgg
>=pAggInfo
->nColumn
){
4560 /* Happens when the left table of a RIGHT JOIN is null and
4561 ** is using an expression index */
4562 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4563 #ifdef SQLITE_VDBE_COVERAGE
4564 /* Verify that the OP_Null above is exercised by tests
4565 ** tag-20230325-2 */
4566 sqlite3VdbeAddOp3(v
, OP_NotNull
, target
, 1, 20230325);
4567 VdbeCoverageNeverTaken(v
);
4571 pCol
= &pAggInfo
->aCol
[pExpr
->iAgg
];
4572 if( !pAggInfo
->directMode
){
4573 return AggInfoColumnReg(pAggInfo
, pExpr
->iAgg
);
4574 }else if( pAggInfo
->useSortingIdx
){
4575 Table
*pTab
= pCol
->pTab
;
4576 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
4577 pCol
->iSorterColumn
, target
);
4579 /* No comment added */
4580 }else if( pCol
->iColumn
<0 ){
4581 VdbeComment((v
,"%s.rowid",pTab
->zName
));
4583 VdbeComment((v
,"%s.%s",
4584 pTab
->zName
, pTab
->aCol
[pCol
->iColumn
].zCnName
));
4585 if( pTab
->aCol
[pCol
->iColumn
].affinity
==SQLITE_AFF_REAL
){
4586 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4590 }else if( pExpr
->y
.pTab
==0 ){
4591 /* This case happens when the argument to an aggregate function
4592 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4593 sqlite3VdbeAddOp3(v
, OP_Column
, pExpr
->iTable
, pExpr
->iColumn
, target
);
4596 /* Otherwise, fall thru into the TK_COLUMN case */
4597 /* no break */ deliberate_fall_through
4600 int iTab
= pExpr
->iTable
;
4602 if( ExprHasProperty(pExpr
, EP_FixedCol
) ){
4603 /* This COLUMN expression is really a constant due to WHERE clause
4604 ** constraints, and that constant is coded by the pExpr->pLeft
4605 ** expression. However, make sure the constant has the correct
4606 ** datatype by applying the Affinity of the table column to the
4610 iReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
,target
);
4611 assert( ExprUseYTab(pExpr
) );
4612 assert( pExpr
->y
.pTab
!=0 );
4613 aff
= sqlite3TableColumnAffinity(pExpr
->y
.pTab
, pExpr
->iColumn
);
4614 if( aff
>SQLITE_AFF_BLOB
){
4615 static const char zAff
[] = "B\000C\000D\000E\000F";
4616 assert( SQLITE_AFF_BLOB
=='A' );
4617 assert( SQLITE_AFF_TEXT
=='B' );
4618 sqlite3VdbeAddOp4(v
, OP_Affinity
, iReg
, 1, 0,
4619 &zAff
[(aff
-'B')*2], P4_STATIC
);
4624 if( pParse
->iSelfTab
<0 ){
4625 /* Other columns in the same row for CHECK constraints or
4626 ** generated columns or for inserting into partial index.
4627 ** The row is unpacked into registers beginning at
4628 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4629 ** immediately prior to the first column.
4634 int iCol
= pExpr
->iColumn
;
4635 assert( ExprUseYTab(pExpr
) );
4636 pTab
= pExpr
->y
.pTab
;
4638 assert( iCol
>=XN_ROWID
);
4639 assert( iCol
<pTab
->nCol
);
4641 return -1-pParse
->iSelfTab
;
4643 pCol
= pTab
->aCol
+ iCol
;
4644 testcase( iCol
!=sqlite3TableColumnToStorage(pTab
,iCol
) );
4645 iSrc
= sqlite3TableColumnToStorage(pTab
, iCol
) - pParse
->iSelfTab
;
4646 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4647 if( pCol
->colFlags
& COLFLAG_GENERATED
){
4648 if( pCol
->colFlags
& COLFLAG_BUSY
){
4649 sqlite3ErrorMsg(pParse
, "generated column loop on \"%s\"",
4653 pCol
->colFlags
|= COLFLAG_BUSY
;
4654 if( pCol
->colFlags
& COLFLAG_NOTAVAIL
){
4655 sqlite3ExprCodeGeneratedColumn(pParse
, pTab
, pCol
, iSrc
);
4657 pCol
->colFlags
&= ~(COLFLAG_BUSY
|COLFLAG_NOTAVAIL
);
4660 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4661 if( pCol
->affinity
==SQLITE_AFF_REAL
){
4662 sqlite3VdbeAddOp2(v
, OP_SCopy
, iSrc
, target
);
4663 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4669 /* Coding an expression that is part of an index where column names
4670 ** in the index refer to the table to which the index belongs */
4671 iTab
= pParse
->iSelfTab
- 1;
4674 else if( pParse
->pIdxPartExpr
4675 && 0!=(r1
= exprPartidxExprLookup(pParse
, pExpr
, target
))
4679 assert( ExprUseYTab(pExpr
) );
4680 assert( pExpr
->y
.pTab
!=0 );
4681 iReg
= sqlite3ExprCodeGetColumn(pParse
, pExpr
->y
.pTab
,
4682 pExpr
->iColumn
, iTab
, target
,
4687 codeInteger(pParse
, pExpr
, 0, target
);
4690 case TK_TRUEFALSE
: {
4691 sqlite3VdbeAddOp2(v
, OP_Integer
, sqlite3ExprTruthValue(pExpr
), target
);
4694 #ifndef SQLITE_OMIT_FLOATING_POINT
4696 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4697 codeReal(v
, pExpr
->u
.zToken
, 0, target
);
4702 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4703 sqlite3VdbeLoadString(v
, target
, pExpr
->u
.zToken
);
4707 /* Make NULL the default case so that if a bug causes an illegal
4708 ** Expr node to be passed into this function, it will be handled
4709 ** sanely and not crash. But keep the assert() to bring the problem
4710 ** to the attention of the developers. */
4711 assert( op
==TK_NULL
|| op
==TK_ERROR
|| pParse
->db
->mallocFailed
);
4712 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4715 #ifndef SQLITE_OMIT_BLOB_LITERAL
4720 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4721 assert( pExpr
->u
.zToken
[0]=='x' || pExpr
->u
.zToken
[0]=='X' );
4722 assert( pExpr
->u
.zToken
[1]=='\'' );
4723 z
= &pExpr
->u
.zToken
[2];
4724 n
= sqlite3Strlen30(z
) - 1;
4725 assert( z
[n
]=='\'' );
4726 zBlob
= sqlite3HexToBlob(sqlite3VdbeDb(v
), z
, n
);
4727 sqlite3VdbeAddOp4(v
, OP_Blob
, n
/2, target
, 0, zBlob
, P4_DYNAMIC
);
4732 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4733 assert( pExpr
->u
.zToken
!=0 );
4734 assert( pExpr
->u
.zToken
[0]!=0 );
4735 sqlite3VdbeAddOp2(v
, OP_Variable
, pExpr
->iColumn
, target
);
4739 return pExpr
->iTable
;
4741 #ifndef SQLITE_OMIT_CAST
4743 /* Expressions of the form: CAST(pLeft AS token) */
4744 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
4745 assert( inReg
==target
);
4746 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4747 sqlite3VdbeAddOp2(v
, OP_Cast
, target
,
4748 sqlite3AffinityType(pExpr
->u
.zToken
, 0));
4751 #endif /* SQLITE_OMIT_CAST */
4754 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
4763 Expr
*pLeft
= pExpr
->pLeft
;
4764 if( sqlite3ExprIsVector(pLeft
) ){
4765 codeVectorCompare(pParse
, pExpr
, target
, op
, p5
);
4767 r1
= sqlite3ExprCodeTemp(pParse
, pLeft
, ®Free1
);
4768 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
4769 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, inReg
);
4770 codeCompare(pParse
, pLeft
, pExpr
->pRight
, op
, r1
, r2
,
4771 sqlite3VdbeCurrentAddr(v
)+2, p5
,
4772 ExprHasProperty(pExpr
,EP_Commuted
));
4773 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
4774 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
4775 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
4776 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
4777 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
4778 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
4779 if( p5
==SQLITE_NULLEQ
){
4780 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, inReg
);
4782 sqlite3VdbeAddOp3(v
, OP_ZeroOrNull
, r1
, inReg
, r2
);
4784 testcase( regFree1
==0 );
4785 testcase( regFree2
==0 );
4801 assert( TK_AND
==OP_And
); testcase( op
==TK_AND
);
4802 assert( TK_OR
==OP_Or
); testcase( op
==TK_OR
);
4803 assert( TK_PLUS
==OP_Add
); testcase( op
==TK_PLUS
);
4804 assert( TK_MINUS
==OP_Subtract
); testcase( op
==TK_MINUS
);
4805 assert( TK_REM
==OP_Remainder
); testcase( op
==TK_REM
);
4806 assert( TK_BITAND
==OP_BitAnd
); testcase( op
==TK_BITAND
);
4807 assert( TK_BITOR
==OP_BitOr
); testcase( op
==TK_BITOR
);
4808 assert( TK_SLASH
==OP_Divide
); testcase( op
==TK_SLASH
);
4809 assert( TK_LSHIFT
==OP_ShiftLeft
); testcase( op
==TK_LSHIFT
);
4810 assert( TK_RSHIFT
==OP_ShiftRight
); testcase( op
==TK_RSHIFT
);
4811 assert( TK_CONCAT
==OP_Concat
); testcase( op
==TK_CONCAT
);
4812 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4813 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
4814 sqlite3VdbeAddOp3(v
, op
, r2
, r1
, target
);
4815 testcase( regFree1
==0 );
4816 testcase( regFree2
==0 );
4820 Expr
*pLeft
= pExpr
->pLeft
;
4822 if( pLeft
->op
==TK_INTEGER
){
4823 codeInteger(pParse
, pLeft
, 1, target
);
4825 #ifndef SQLITE_OMIT_FLOATING_POINT
4826 }else if( pLeft
->op
==TK_FLOAT
){
4827 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4828 codeReal(v
, pLeft
->u
.zToken
, 1, target
);
4832 tempX
.op
= TK_INTEGER
;
4833 tempX
.flags
= EP_IntValue
|EP_TokenOnly
;
4835 ExprClearVVAProperties(&tempX
);
4836 r1
= sqlite3ExprCodeTemp(pParse
, &tempX
, ®Free1
);
4837 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free2
);
4838 sqlite3VdbeAddOp3(v
, OP_Subtract
, r2
, r1
, target
);
4839 testcase( regFree2
==0 );
4845 assert( TK_BITNOT
==OP_BitNot
); testcase( op
==TK_BITNOT
);
4846 assert( TK_NOT
==OP_Not
); testcase( op
==TK_NOT
);
4847 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4848 testcase( regFree1
==0 );
4849 sqlite3VdbeAddOp2(v
, op
, r1
, inReg
);
4853 int isTrue
; /* IS TRUE or IS NOT TRUE */
4854 int bNormal
; /* IS TRUE or IS FALSE */
4855 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4856 testcase( regFree1
==0 );
4857 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
4858 bNormal
= pExpr
->op2
==TK_IS
;
4859 testcase( isTrue
&& bNormal
);
4860 testcase( !isTrue
&& bNormal
);
4861 sqlite3VdbeAddOp4Int(v
, OP_IsTrue
, r1
, inReg
, !isTrue
, isTrue
^ bNormal
);
4867 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
4868 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
4869 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
4870 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4871 testcase( regFree1
==0 );
4872 addr
= sqlite3VdbeAddOp1(v
, op
, r1
);
4873 VdbeCoverageIf(v
, op
==TK_ISNULL
);
4874 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
4875 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, target
);
4876 sqlite3VdbeJumpHere(v
, addr
);
4879 case TK_AGG_FUNCTION
: {
4880 AggInfo
*pInfo
= pExpr
->pAggInfo
;
4882 || NEVER(pExpr
->iAgg
<0)
4883 || NEVER(pExpr
->iAgg
>=pInfo
->nFunc
)
4885 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4886 sqlite3ErrorMsg(pParse
, "misuse of aggregate: %#T()", pExpr
);
4888 return AggInfoFuncReg(pInfo
, pExpr
->iAgg
);
4893 ExprList
*pFarg
; /* List of function arguments */
4894 int nFarg
; /* Number of function arguments */
4895 FuncDef
*pDef
; /* The function definition object */
4896 const char *zId
; /* The function name */
4897 u32 constMask
= 0; /* Mask of function arguments that are constant */
4898 int i
; /* Loop counter */
4899 sqlite3
*db
= pParse
->db
; /* The database connection */
4900 u8 enc
= ENC(db
); /* The text encoding used by this database */
4901 CollSeq
*pColl
= 0; /* A collating sequence */
4903 #ifndef SQLITE_OMIT_WINDOWFUNC
4904 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
4905 return pExpr
->y
.pWin
->regResult
;
4909 if( ConstFactorOk(pParse
)
4910 && sqlite3ExprIsConstantNotJoin(pParse
,pExpr
)
4912 /* SQL functions can be expensive. So try to avoid running them
4913 ** multiple times if we know they always give the same result */
4914 return sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, -1);
4916 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
) );
4917 assert( ExprUseXList(pExpr
) );
4918 pFarg
= pExpr
->x
.pList
;
4919 nFarg
= pFarg
? pFarg
->nExpr
: 0;
4920 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4921 zId
= pExpr
->u
.zToken
;
4922 pDef
= sqlite3FindFunction(db
, zId
, nFarg
, enc
, 0);
4923 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4924 if( pDef
==0 && pParse
->explain
){
4925 pDef
= sqlite3FindFunction(db
, "unknown", nFarg
, enc
, 0);
4928 if( pDef
==0 || pDef
->xFinalize
!=0 ){
4929 sqlite3ErrorMsg(pParse
, "unknown function: %#T()", pExpr
);
4932 if( (pDef
->funcFlags
& SQLITE_FUNC_INLINE
)!=0 && ALWAYS(pFarg
!=0) ){
4933 assert( (pDef
->funcFlags
& SQLITE_FUNC_UNSAFE
)==0 );
4934 assert( (pDef
->funcFlags
& SQLITE_FUNC_DIRECT
)==0 );
4935 return exprCodeInlineFunction(pParse
, pFarg
,
4936 SQLITE_PTR_TO_INT(pDef
->pUserData
), target
);
4937 }else if( pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
) ){
4938 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
4941 for(i
=0; i
<nFarg
; i
++){
4942 if( i
<32 && sqlite3ExprIsConstant(pParse
, pFarg
->a
[i
].pExpr
) ){
4944 constMask
|= MASKBIT32(i
);
4946 if( (pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
)!=0 && !pColl
){
4947 pColl
= sqlite3ExprCollSeq(pParse
, pFarg
->a
[i
].pExpr
);
4952 r1
= pParse
->nMem
+1;
4953 pParse
->nMem
+= nFarg
;
4955 r1
= sqlite3GetTempRange(pParse
, nFarg
);
4958 /* For length() and typeof() and octet_length() functions,
4959 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4960 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid
4961 ** unnecessary data loading.
4963 if( (pDef
->funcFlags
& (SQLITE_FUNC_LENGTH
|SQLITE_FUNC_TYPEOF
))!=0 ){
4966 assert( pFarg
->a
[0].pExpr
!=0 );
4967 exprOp
= pFarg
->a
[0].pExpr
->op
;
4968 if( exprOp
==TK_COLUMN
|| exprOp
==TK_AGG_COLUMN
){
4969 assert( SQLITE_FUNC_LENGTH
==OPFLAG_LENGTHARG
);
4970 assert( SQLITE_FUNC_TYPEOF
==OPFLAG_TYPEOFARG
);
4971 assert( SQLITE_FUNC_BYTELEN
==OPFLAG_BYTELENARG
);
4972 assert( (OPFLAG_LENGTHARG
|OPFLAG_TYPEOFARG
)==OPFLAG_BYTELENARG
);
4973 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_LENGTHARG
);
4974 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_TYPEOFARG
);
4975 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_BYTELENARG
);
4976 pFarg
->a
[0].pExpr
->op2
= pDef
->funcFlags
& OPFLAG_BYTELENARG
;
4980 sqlite3ExprCodeExprList(pParse
, pFarg
, r1
, 0, SQLITE_ECEL_FACTOR
);
4984 #ifndef SQLITE_OMIT_VIRTUALTABLE
4985 /* Possibly overload the function if the first argument is
4986 ** a virtual table column.
4988 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4989 ** second argument, not the first, as the argument to test to
4990 ** see if it is a column in a virtual table. This is done because
4991 ** the left operand of infix functions (the operand we want to
4992 ** control overloading) ends up as the second argument to the
4993 ** function. The expression "A glob B" is equivalent to
4994 ** "glob(B,A). We want to use the A in "A glob B" to test
4995 ** for function overloading. But we use the B term in "glob(B,A)".
4997 if( nFarg
>=2 && ExprHasProperty(pExpr
, EP_InfixFunc
) ){
4998 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[1].pExpr
);
4999 }else if( nFarg
>0 ){
5000 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[0].pExpr
);
5003 if( pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
){
5004 if( !pColl
) pColl
= db
->pDfltColl
;
5005 sqlite3VdbeAddOp4(v
, OP_CollSeq
, 0, 0, 0, (char *)pColl
, P4_COLLSEQ
);
5007 sqlite3VdbeAddFunctionCall(pParse
, constMask
, r1
, target
, nFarg
,
5011 sqlite3ReleaseTempRange(pParse
, r1
, nFarg
);
5013 sqlite3VdbeReleaseRegisters(pParse
, r1
, nFarg
, constMask
, 1);
5018 #ifndef SQLITE_OMIT_SUBQUERY
5022 testcase( op
==TK_EXISTS
);
5023 testcase( op
==TK_SELECT
);
5024 if( pParse
->db
->mallocFailed
){
5026 }else if( op
==TK_SELECT
5027 && ALWAYS( ExprUseXSelect(pExpr
) )
5028 && (nCol
= pExpr
->x
.pSelect
->pEList
->nExpr
)!=1
5030 sqlite3SubselectError(pParse
, nCol
, 1);
5032 return sqlite3CodeSubselect(pParse
, pExpr
);
5036 case TK_SELECT_COLUMN
: {
5038 Expr
*pLeft
= pExpr
->pLeft
;
5039 if( pLeft
->iTable
==0 || pParse
->withinRJSubrtn
> pLeft
->op2
){
5040 pLeft
->iTable
= sqlite3CodeSubselect(pParse
, pLeft
);
5041 pLeft
->op2
= pParse
->withinRJSubrtn
;
5043 assert( pLeft
->op
==TK_SELECT
|| pLeft
->op
==TK_ERROR
);
5044 n
= sqlite3ExprVectorSize(pLeft
);
5045 if( pExpr
->iTable
!=n
){
5046 sqlite3ErrorMsg(pParse
, "%d columns assigned %d values",
5049 return pLeft
->iTable
+ pExpr
->iColumn
;
5052 int destIfFalse
= sqlite3VdbeMakeLabel(pParse
);
5053 int destIfNull
= sqlite3VdbeMakeLabel(pParse
);
5054 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
5055 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
5056 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
5057 sqlite3VdbeResolveLabel(v
, destIfFalse
);
5058 sqlite3VdbeAddOp2(v
, OP_AddImm
, target
, 0);
5059 sqlite3VdbeResolveLabel(v
, destIfNull
);
5062 #endif /* SQLITE_OMIT_SUBQUERY */
5066 ** x BETWEEN y AND z
5068 ** This is equivalent to
5072 ** X is stored in pExpr->pLeft.
5073 ** Y is stored in pExpr->pList->a[0].pExpr.
5074 ** Z is stored in pExpr->pList->a[1].pExpr.
5077 exprCodeBetween(pParse
, pExpr
, target
, 0, 0);
5081 if( !ExprHasProperty(pExpr
, EP_Collate
) ){
5082 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
5083 ** "SOFT-COLLATE" that is added to constraints that are pushed down
5084 ** from outer queries into sub-queries by the WHERE-clause push-down
5085 ** optimization. Clear subtypes as subtypes may not cross a subquery
5088 assert( pExpr
->pLeft
);
5089 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
5090 sqlite3VdbeAddOp1(v
, OP_ClrSubtype
, target
);
5093 pExpr
= pExpr
->pLeft
;
5094 goto expr_code_doover
; /* 2018-04-28: Prevent deep recursion. */
5099 pExpr
= pExpr
->pLeft
;
5100 goto expr_code_doover
; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
5104 /* If the opcode is TK_TRIGGER, then the expression is a reference
5105 ** to a column in the new.* or old.* pseudo-tables available to
5106 ** trigger programs. In this case Expr.iTable is set to 1 for the
5107 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
5108 ** is set to the column of the pseudo-table to read, or to -1 to
5109 ** read the rowid field.
5111 ** The expression is implemented using an OP_Param opcode. The p1
5112 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
5113 ** to reference another column of the old.* pseudo-table, where
5114 ** i is the index of the column. For a new.rowid reference, p1 is
5115 ** set to (n+1), where n is the number of columns in each pseudo-table.
5116 ** For a reference to any other column in the new.* pseudo-table, p1
5117 ** is set to (n+2+i), where n and i are as defined previously. For
5118 ** example, if the table on which triggers are being fired is
5121 ** CREATE TABLE t1(a, b);
5123 ** Then p1 is interpreted as follows:
5125 ** p1==0 -> old.rowid p1==3 -> new.rowid
5126 ** p1==1 -> old.a p1==4 -> new.a
5127 ** p1==2 -> old.b p1==5 -> new.b
5133 assert( ExprUseYTab(pExpr
) );
5134 pTab
= pExpr
->y
.pTab
;
5135 iCol
= pExpr
->iColumn
;
5136 p1
= pExpr
->iTable
* (pTab
->nCol
+1) + 1
5137 + sqlite3TableColumnToStorage(pTab
, iCol
);
5139 assert( pExpr
->iTable
==0 || pExpr
->iTable
==1 );
5140 assert( iCol
>=-1 && iCol
<pTab
->nCol
);
5141 assert( pTab
->iPKey
<0 || iCol
!=pTab
->iPKey
);
5142 assert( p1
>=0 && p1
<(pTab
->nCol
*2+2) );
5144 sqlite3VdbeAddOp2(v
, OP_Param
, p1
, target
);
5145 VdbeComment((v
, "r[%d]=%s.%s", target
,
5146 (pExpr
->iTable
? "new" : "old"),
5147 (pExpr
->iColumn
<0 ? "rowid" : pExpr
->y
.pTab
->aCol
[iCol
].zCnName
)
5150 #ifndef SQLITE_OMIT_FLOATING_POINT
5151 /* If the column has REAL affinity, it may currently be stored as an
5152 ** integer. Use OP_RealAffinity to make sure it is really real.
5154 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
5155 ** floating point when extracting it from the record. */
5156 if( iCol
>=0 && pTab
->aCol
[iCol
].affinity
==SQLITE_AFF_REAL
){
5157 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
5164 sqlite3ErrorMsg(pParse
, "row value misused");
5168 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
5169 ** that derive from the right-hand table of a LEFT JOIN. The
5170 ** Expr.iTable value is the table number for the right-hand table.
5171 ** The expression is only evaluated if that table is not currently
5172 ** on a LEFT JOIN NULL row.
5174 case TK_IF_NULL_ROW
: {
5176 u8 okConstFactor
= pParse
->okConstFactor
;
5177 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
5179 assert( pExpr
->iAgg
>=0 && pExpr
->iAgg
<pAggInfo
->nColumn
);
5180 if( !pAggInfo
->directMode
){
5181 inReg
= AggInfoColumnReg(pAggInfo
, pExpr
->iAgg
);
5184 if( pExpr
->pAggInfo
->useSortingIdx
){
5185 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
5186 pAggInfo
->aCol
[pExpr
->iAgg
].iSorterColumn
,
5192 addrINR
= sqlite3VdbeAddOp3(v
, OP_IfNullRow
, pExpr
->iTable
, 0, target
);
5193 /* The OP_IfNullRow opcode above can overwrite the result register with
5194 ** NULL. So we have to ensure that the result register is not a value
5195 ** that is suppose to be a constant. Two defenses are needed:
5196 ** (1) Temporarily disable factoring of constant expressions
5197 ** (2) Make sure the computed value really is stored in register
5198 ** "target" and not someplace else.
5200 pParse
->okConstFactor
= 0; /* note (1) above */
5201 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
5202 assert( target
==inReg
);
5203 pParse
->okConstFactor
= okConstFactor
;
5204 sqlite3VdbeJumpHere(v
, addrINR
);
5210 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5213 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5215 ** Form A is can be transformed into the equivalent form B as follows:
5216 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
5217 ** WHEN x=eN THEN rN ELSE y END
5219 ** X (if it exists) is in pExpr->pLeft.
5220 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
5221 ** odd. The Y is also optional. If the number of elements in x.pList
5222 ** is even, then Y is omitted and the "otherwise" result is NULL.
5223 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
5225 ** The result of the expression is the Ri for the first matching Ei,
5226 ** or if there is no matching Ei, the ELSE term Y, or if there is
5227 ** no ELSE term, NULL.
5230 int endLabel
; /* GOTO label for end of CASE stmt */
5231 int nextCase
; /* GOTO label for next WHEN clause */
5232 int nExpr
; /* 2x number of WHEN terms */
5233 int i
; /* Loop counter */
5234 ExprList
*pEList
; /* List of WHEN terms */
5235 struct ExprList_item
*aListelem
; /* Array of WHEN terms */
5236 Expr opCompare
; /* The X==Ei expression */
5237 Expr
*pX
; /* The X expression */
5238 Expr
*pTest
= 0; /* X==Ei (form A) or just Ei (form B) */
5240 sqlite3
*db
= pParse
->db
;
5242 assert( ExprUseXList(pExpr
) && pExpr
->x
.pList
!=0 );
5243 assert(pExpr
->x
.pList
->nExpr
> 0);
5244 pEList
= pExpr
->x
.pList
;
5245 aListelem
= pEList
->a
;
5246 nExpr
= pEList
->nExpr
;
5247 endLabel
= sqlite3VdbeMakeLabel(pParse
);
5248 if( (pX
= pExpr
->pLeft
)!=0 ){
5249 pDel
= sqlite3ExprDup(db
, pX
, 0);
5250 if( db
->mallocFailed
){
5251 sqlite3ExprDelete(db
, pDel
);
5254 testcase( pX
->op
==TK_COLUMN
);
5255 exprToRegister(pDel
, exprCodeVector(pParse
, pDel
, ®Free1
));
5256 testcase( regFree1
==0 );
5257 memset(&opCompare
, 0, sizeof(opCompare
));
5258 opCompare
.op
= TK_EQ
;
5259 opCompare
.pLeft
= pDel
;
5261 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
5262 ** The value in regFree1 might get SCopy-ed into the file result.
5263 ** So make sure that the regFree1 register is not reused for other
5264 ** purposes and possibly overwritten. */
5267 for(i
=0; i
<nExpr
-1; i
=i
+2){
5270 opCompare
.pRight
= aListelem
[i
].pExpr
;
5272 pTest
= aListelem
[i
].pExpr
;
5274 nextCase
= sqlite3VdbeMakeLabel(pParse
);
5275 testcase( pTest
->op
==TK_COLUMN
);
5276 sqlite3ExprIfFalse(pParse
, pTest
, nextCase
, SQLITE_JUMPIFNULL
);
5277 testcase( aListelem
[i
+1].pExpr
->op
==TK_COLUMN
);
5278 sqlite3ExprCode(pParse
, aListelem
[i
+1].pExpr
, target
);
5279 sqlite3VdbeGoto(v
, endLabel
);
5280 sqlite3VdbeResolveLabel(v
, nextCase
);
5283 sqlite3ExprCode(pParse
, pEList
->a
[nExpr
-1].pExpr
, target
);
5285 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
5287 sqlite3ExprDelete(db
, pDel
);
5288 setDoNotMergeFlagOnCopy(v
);
5289 sqlite3VdbeResolveLabel(v
, endLabel
);
5292 #ifndef SQLITE_OMIT_TRIGGER
5294 assert( pExpr
->affExpr
==OE_Rollback
5295 || pExpr
->affExpr
==OE_Abort
5296 || pExpr
->affExpr
==OE_Fail
5297 || pExpr
->affExpr
==OE_Ignore
5299 if( !pParse
->pTriggerTab
&& !pParse
->nested
){
5300 sqlite3ErrorMsg(pParse
,
5301 "RAISE() may only be used within a trigger-program");
5304 if( pExpr
->affExpr
==OE_Abort
){
5305 sqlite3MayAbort(pParse
);
5307 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
5308 if( pExpr
->affExpr
==OE_Ignore
){
5310 v
, OP_Halt
, SQLITE_OK
, OE_Ignore
, 0, pExpr
->u
.zToken
,0);
5313 sqlite3HaltConstraint(pParse
,
5314 pParse
->pTriggerTab
? SQLITE_CONSTRAINT_TRIGGER
: SQLITE_ERROR
,
5315 pExpr
->affExpr
, pExpr
->u
.zToken
, 0, 0);
5322 sqlite3ReleaseTempReg(pParse
, regFree1
);
5323 sqlite3ReleaseTempReg(pParse
, regFree2
);
5328 ** Generate code that will evaluate expression pExpr just one time
5329 ** per prepared statement execution.
5331 ** If the expression uses functions (that might throw an exception) then
5332 ** guard them with an OP_Once opcode to ensure that the code is only executed
5333 ** once. If no functions are involved, then factor the code out and put it at
5334 ** the end of the prepared statement in the initialization section.
5336 ** If regDest>0 then the result is always stored in that register and the
5337 ** result is not reusable. If regDest<0 then this routine is free to
5338 ** store the value wherever it wants. The register where the expression
5339 ** is stored is returned. When regDest<0, two identical expressions might
5340 ** code to the same register, if they do not contain function calls and hence
5341 ** are factored out into the initialization section at the end of the
5342 ** prepared statement.
5344 int sqlite3ExprCodeRunJustOnce(
5345 Parse
*pParse
, /* Parsing context */
5346 Expr
*pExpr
, /* The expression to code when the VDBE initializes */
5347 int regDest
/* Store the value in this register */
5350 assert( ConstFactorOk(pParse
) );
5351 assert( regDest
!=0 );
5352 p
= pParse
->pConstExpr
;
5353 if( regDest
<0 && p
){
5354 struct ExprList_item
*pItem
;
5356 for(pItem
=p
->a
, i
=p
->nExpr
; i
>0; pItem
++, i
--){
5357 if( pItem
->fg
.reusable
5358 && sqlite3ExprCompare(0,pItem
->pExpr
,pExpr
,-1)==0
5360 return pItem
->u
.iConstExprReg
;
5364 pExpr
= sqlite3ExprDup(pParse
->db
, pExpr
, 0);
5365 if( pExpr
!=0 && ExprHasProperty(pExpr
, EP_HasFunc
) ){
5366 Vdbe
*v
= pParse
->pVdbe
;
5369 addr
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
5370 pParse
->okConstFactor
= 0;
5371 if( !pParse
->db
->mallocFailed
){
5372 if( regDest
<0 ) regDest
= ++pParse
->nMem
;
5373 sqlite3ExprCode(pParse
, pExpr
, regDest
);
5375 pParse
->okConstFactor
= 1;
5376 sqlite3ExprDelete(pParse
->db
, pExpr
);
5377 sqlite3VdbeJumpHere(v
, addr
);
5379 p
= sqlite3ExprListAppend(pParse
, p
, pExpr
);
5381 struct ExprList_item
*pItem
= &p
->a
[p
->nExpr
-1];
5382 pItem
->fg
.reusable
= regDest
<0;
5383 if( regDest
<0 ) regDest
= ++pParse
->nMem
;
5384 pItem
->u
.iConstExprReg
= regDest
;
5386 pParse
->pConstExpr
= p
;
5392 ** Generate code to evaluate an expression and store the results
5393 ** into a register. Return the register number where the results
5396 ** If the register is a temporary register that can be deallocated,
5397 ** then write its number into *pReg. If the result register is not
5398 ** a temporary, then set *pReg to zero.
5400 ** If pExpr is a constant, then this routine might generate this
5401 ** code to fill the register in the initialization section of the
5402 ** VDBE program, in order to factor it out of the evaluation loop.
5404 int sqlite3ExprCodeTemp(Parse
*pParse
, Expr
*pExpr
, int *pReg
){
5406 pExpr
= sqlite3ExprSkipCollateAndLikely(pExpr
);
5407 if( ConstFactorOk(pParse
)
5409 && pExpr
->op
!=TK_REGISTER
5410 && sqlite3ExprIsConstantNotJoin(pParse
, pExpr
)
5413 r2
= sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, -1);
5415 int r1
= sqlite3GetTempReg(pParse
);
5416 r2
= sqlite3ExprCodeTarget(pParse
, pExpr
, r1
);
5420 sqlite3ReleaseTempReg(pParse
, r1
);
5428 ** Generate code that will evaluate expression pExpr and store the
5429 ** results in register target. The results are guaranteed to appear
5430 ** in register target.
5432 void sqlite3ExprCode(Parse
*pParse
, Expr
*pExpr
, int target
){
5435 assert( pExpr
==0 || !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
5436 assert( target
>0 && target
<=pParse
->nMem
);
5437 assert( pParse
->pVdbe
!=0 || pParse
->db
->mallocFailed
);
5438 if( pParse
->pVdbe
==0 ) return;
5439 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
);
5440 if( inReg
!=target
){
5442 Expr
*pX
= sqlite3ExprSkipCollateAndLikely(pExpr
);
5443 testcase( pX
!=pExpr
);
5445 && (ExprHasProperty(pX
,EP_Subquery
) || pX
->op
==TK_REGISTER
)
5451 sqlite3VdbeAddOp2(pParse
->pVdbe
, op
, inReg
, target
);
5456 ** Make a transient copy of expression pExpr and then code it using
5457 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5458 ** except that the input expression is guaranteed to be unchanged.
5460 void sqlite3ExprCodeCopy(Parse
*pParse
, Expr
*pExpr
, int target
){
5461 sqlite3
*db
= pParse
->db
;
5462 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
5463 if( !db
->mallocFailed
) sqlite3ExprCode(pParse
, pExpr
, target
);
5464 sqlite3ExprDelete(db
, pExpr
);
5468 ** Generate code that will evaluate expression pExpr and store the
5469 ** results in register target. The results are guaranteed to appear
5470 ** in register target. If the expression is constant, then this routine
5471 ** might choose to code the expression at initialization time.
5473 void sqlite3ExprCodeFactorable(Parse
*pParse
, Expr
*pExpr
, int target
){
5474 if( pParse
->okConstFactor
&& sqlite3ExprIsConstantNotJoin(pParse
,pExpr
) ){
5475 sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, target
);
5477 sqlite3ExprCodeCopy(pParse
, pExpr
, target
);
5482 ** Generate code that pushes the value of every element of the given
5483 ** expression list into a sequence of registers beginning at target.
5485 ** Return the number of elements evaluated. The number returned will
5486 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5489 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5490 ** filled using OP_SCopy. OP_Copy must be used instead.
5492 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5493 ** factored out into initialization code.
5495 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5496 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5497 ** in registers at srcReg, and so the value can be copied from there.
5498 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5499 ** are simply omitted rather than being copied from srcReg.
5501 int sqlite3ExprCodeExprList(
5502 Parse
*pParse
, /* Parsing context */
5503 ExprList
*pList
, /* The expression list to be coded */
5504 int target
, /* Where to write results */
5505 int srcReg
, /* Source registers if SQLITE_ECEL_REF */
5506 u8 flags
/* SQLITE_ECEL_* flags */
5508 struct ExprList_item
*pItem
;
5510 u8 copyOp
= (flags
& SQLITE_ECEL_DUP
) ? OP_Copy
: OP_SCopy
;
5511 Vdbe
*v
= pParse
->pVdbe
;
5514 assert( pParse
->pVdbe
!=0 ); /* Never gets this far otherwise */
5516 if( !ConstFactorOk(pParse
) ) flags
&= ~SQLITE_ECEL_FACTOR
;
5517 for(pItem
=pList
->a
, i
=0; i
<n
; i
++, pItem
++){
5518 Expr
*pExpr
= pItem
->pExpr
;
5519 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5520 if( pItem
->fg
.bSorterRef
){
5525 if( (flags
& SQLITE_ECEL_REF
)!=0 && (j
= pItem
->u
.x
.iOrderByCol
)>0 ){
5526 if( flags
& SQLITE_ECEL_OMITREF
){
5530 sqlite3VdbeAddOp2(v
, copyOp
, j
+srcReg
-1, target
+i
);
5532 }else if( (flags
& SQLITE_ECEL_FACTOR
)!=0
5533 && sqlite3ExprIsConstantNotJoin(pParse
,pExpr
)
5535 sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, target
+i
);
5537 int inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
+i
);
5538 if( inReg
!=target
+i
){
5541 && (pOp
=sqlite3VdbeGetLastOp(v
))->opcode
==OP_Copy
5542 && pOp
->p1
+pOp
->p3
+1==inReg
5543 && pOp
->p2
+pOp
->p3
+1==target
+i
5544 && pOp
->p5
==0 /* The do-not-merge flag must be clear */
5548 sqlite3VdbeAddOp2(v
, copyOp
, inReg
, target
+i
);
5557 ** Generate code for a BETWEEN operator.
5559 ** x BETWEEN y AND z
5561 ** The above is equivalent to
5565 ** Code it as such, taking care to do the common subexpression
5566 ** elimination of x.
5568 ** The xJumpIf parameter determines details:
5570 ** NULL: Store the boolean result in reg[dest]
5571 ** sqlite3ExprIfTrue: Jump to dest if true
5572 ** sqlite3ExprIfFalse: Jump to dest if false
5574 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5576 static void exprCodeBetween(
5577 Parse
*pParse
, /* Parsing and code generating context */
5578 Expr
*pExpr
, /* The BETWEEN expression */
5579 int dest
, /* Jump destination or storage location */
5580 void (*xJump
)(Parse
*,Expr
*,int,int), /* Action to take */
5581 int jumpIfNull
/* Take the jump if the BETWEEN is NULL */
5583 Expr exprAnd
; /* The AND operator in x>=y AND x<=z */
5584 Expr compLeft
; /* The x>=y term */
5585 Expr compRight
; /* The x<=z term */
5586 int regFree1
= 0; /* Temporary use register */
5588 sqlite3
*db
= pParse
->db
;
5590 memset(&compLeft
, 0, sizeof(Expr
));
5591 memset(&compRight
, 0, sizeof(Expr
));
5592 memset(&exprAnd
, 0, sizeof(Expr
));
5594 assert( ExprUseXList(pExpr
) );
5595 pDel
= sqlite3ExprDup(db
, pExpr
->pLeft
, 0);
5596 if( db
->mallocFailed
==0 ){
5597 exprAnd
.op
= TK_AND
;
5598 exprAnd
.pLeft
= &compLeft
;
5599 exprAnd
.pRight
= &compRight
;
5600 compLeft
.op
= TK_GE
;
5601 compLeft
.pLeft
= pDel
;
5602 compLeft
.pRight
= pExpr
->x
.pList
->a
[0].pExpr
;
5603 compRight
.op
= TK_LE
;
5604 compRight
.pLeft
= pDel
;
5605 compRight
.pRight
= pExpr
->x
.pList
->a
[1].pExpr
;
5606 exprToRegister(pDel
, exprCodeVector(pParse
, pDel
, ®Free1
));
5608 xJump(pParse
, &exprAnd
, dest
, jumpIfNull
);
5610 /* Mark the expression is being from the ON or USING clause of a join
5611 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5612 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5613 ** for clarity, but we are out of bits in the Expr.flags field so we
5614 ** have to reuse the EP_OuterON bit. Bummer. */
5615 pDel
->flags
|= EP_OuterON
;
5616 sqlite3ExprCodeTarget(pParse
, &exprAnd
, dest
);
5618 sqlite3ReleaseTempReg(pParse
, regFree1
);
5620 sqlite3ExprDelete(db
, pDel
);
5622 /* Ensure adequate test coverage */
5623 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
==0 && regFree1
==0 );
5624 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
==0 && regFree1
!=0 );
5625 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
!=0 && regFree1
==0 );
5626 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
!=0 && regFree1
!=0 );
5627 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
==0 && regFree1
==0 );
5628 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
==0 && regFree1
!=0 );
5629 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
!=0 && regFree1
==0 );
5630 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
!=0 && regFree1
!=0 );
5631 testcase( xJump
==0 );
5635 ** Generate code for a boolean expression such that a jump is made
5636 ** to the label "dest" if the expression is true but execution
5637 ** continues straight thru if the expression is false.
5639 ** If the expression evaluates to NULL (neither true nor false), then
5640 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5642 ** This code depends on the fact that certain token values (ex: TK_EQ)
5643 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5644 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5645 ** the make process cause these values to align. Assert()s in the code
5646 ** below verify that the numbers are aligned correctly.
5648 void sqlite3ExprIfTrue(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
5649 Vdbe
*v
= pParse
->pVdbe
;
5655 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
5656 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
5657 if( NEVER(pExpr
==0) ) return; /* No way this can happen */
5658 assert( !ExprHasVVAProperty(pExpr
, EP_Immutable
) );
5663 Expr
*pAlt
= sqlite3ExprSimplifiedAndOr(pExpr
);
5665 sqlite3ExprIfTrue(pParse
, pAlt
, dest
, jumpIfNull
);
5666 }else if( op
==TK_AND
){
5667 int d2
= sqlite3VdbeMakeLabel(pParse
);
5668 testcase( jumpIfNull
==0 );
5669 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, d2
,
5670 jumpIfNull
^SQLITE_JUMPIFNULL
);
5671 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5672 sqlite3VdbeResolveLabel(v
, d2
);
5674 testcase( jumpIfNull
==0 );
5675 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5676 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5681 testcase( jumpIfNull
==0 );
5682 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5686 int isNot
; /* IS NOT TRUE or IS NOT FALSE */
5687 int isTrue
; /* IS TRUE or IS NOT TRUE */
5688 testcase( jumpIfNull
==0 );
5689 isNot
= pExpr
->op2
==TK_ISNOT
;
5690 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
5691 testcase( isTrue
&& isNot
);
5692 testcase( !isTrue
&& isNot
);
5693 if( isTrue
^ isNot
){
5694 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
,
5695 isNot
? SQLITE_JUMPIFNULL
: 0);
5697 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
,
5698 isNot
? SQLITE_JUMPIFNULL
: 0);
5704 testcase( op
==TK_IS
);
5705 testcase( op
==TK_ISNOT
);
5706 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
5707 jumpIfNull
= SQLITE_NULLEQ
;
5708 /* no break */ deliberate_fall_through
5715 if( sqlite3ExprIsVector(pExpr
->pLeft
) ) goto default_expr
;
5716 testcase( jumpIfNull
==0 );
5717 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5718 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
5719 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
5720 r1
, r2
, dest
, jumpIfNull
, ExprHasProperty(pExpr
,EP_Commuted
));
5721 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
5722 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
5723 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
5724 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
5725 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
);
5726 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
==SQLITE_NULLEQ
);
5727 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
!=SQLITE_NULLEQ
);
5728 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
);
5729 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
==SQLITE_NULLEQ
);
5730 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
!=SQLITE_NULLEQ
);
5731 testcase( regFree1
==0 );
5732 testcase( regFree2
==0 );
5737 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
5738 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
5739 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5740 sqlite3VdbeTypeofColumn(v
, r1
);
5741 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
5742 VdbeCoverageIf(v
, op
==TK_ISNULL
);
5743 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
5744 testcase( regFree1
==0 );
5748 testcase( jumpIfNull
==0 );
5749 exprCodeBetween(pParse
, pExpr
, dest
, sqlite3ExprIfTrue
, jumpIfNull
);
5752 #ifndef SQLITE_OMIT_SUBQUERY
5754 int destIfFalse
= sqlite3VdbeMakeLabel(pParse
);
5755 int destIfNull
= jumpIfNull
? dest
: destIfFalse
;
5756 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
5757 sqlite3VdbeGoto(v
, dest
);
5758 sqlite3VdbeResolveLabel(v
, destIfFalse
);
5764 if( ExprAlwaysTrue(pExpr
) ){
5765 sqlite3VdbeGoto(v
, dest
);
5766 }else if( ExprAlwaysFalse(pExpr
) ){
5769 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
5770 sqlite3VdbeAddOp3(v
, OP_If
, r1
, dest
, jumpIfNull
!=0);
5772 testcase( regFree1
==0 );
5773 testcase( jumpIfNull
==0 );
5778 sqlite3ReleaseTempReg(pParse
, regFree1
);
5779 sqlite3ReleaseTempReg(pParse
, regFree2
);
5783 ** Generate code for a boolean expression such that a jump is made
5784 ** to the label "dest" if the expression is false but execution
5785 ** continues straight thru if the expression is true.
5787 ** If the expression evaluates to NULL (neither true nor false) then
5788 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5791 void sqlite3ExprIfFalse(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
5792 Vdbe
*v
= pParse
->pVdbe
;
5798 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
5799 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
5800 if( pExpr
==0 ) return;
5801 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
5803 /* The value of pExpr->op and op are related as follows:
5806 ** --------- ----------
5807 ** TK_ISNULL OP_NotNull
5808 ** TK_NOTNULL OP_IsNull
5816 ** For other values of pExpr->op, op is undefined and unused.
5817 ** The value of TK_ and OP_ constants are arranged such that we
5818 ** can compute the mapping above using the following expression.
5819 ** Assert()s verify that the computation is correct.
5821 op
= ((pExpr
->op
+(TK_ISNULL
&1))^1)-(TK_ISNULL
&1);
5823 /* Verify correct alignment of TK_ and OP_ constants
5825 assert( pExpr
->op
!=TK_ISNULL
|| op
==OP_NotNull
);
5826 assert( pExpr
->op
!=TK_NOTNULL
|| op
==OP_IsNull
);
5827 assert( pExpr
->op
!=TK_NE
|| op
==OP_Eq
);
5828 assert( pExpr
->op
!=TK_EQ
|| op
==OP_Ne
);
5829 assert( pExpr
->op
!=TK_LT
|| op
==OP_Ge
);
5830 assert( pExpr
->op
!=TK_LE
|| op
==OP_Gt
);
5831 assert( pExpr
->op
!=TK_GT
|| op
==OP_Le
);
5832 assert( pExpr
->op
!=TK_GE
|| op
==OP_Lt
);
5834 switch( pExpr
->op
){
5837 Expr
*pAlt
= sqlite3ExprSimplifiedAndOr(pExpr
);
5839 sqlite3ExprIfFalse(pParse
, pAlt
, dest
, jumpIfNull
);
5840 }else if( pExpr
->op
==TK_AND
){
5841 testcase( jumpIfNull
==0 );
5842 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5843 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5845 int d2
= sqlite3VdbeMakeLabel(pParse
);
5846 testcase( jumpIfNull
==0 );
5847 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, d2
,
5848 jumpIfNull
^SQLITE_JUMPIFNULL
);
5849 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5850 sqlite3VdbeResolveLabel(v
, d2
);
5855 testcase( jumpIfNull
==0 );
5856 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5860 int isNot
; /* IS NOT TRUE or IS NOT FALSE */
5861 int isTrue
; /* IS TRUE or IS NOT TRUE */
5862 testcase( jumpIfNull
==0 );
5863 isNot
= pExpr
->op2
==TK_ISNOT
;
5864 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
5865 testcase( isTrue
&& isNot
);
5866 testcase( !isTrue
&& isNot
);
5867 if( isTrue
^ isNot
){
5868 /* IS TRUE and IS NOT FALSE */
5869 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
,
5870 isNot
? 0 : SQLITE_JUMPIFNULL
);
5873 /* IS FALSE and IS NOT TRUE */
5874 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
,
5875 isNot
? 0 : SQLITE_JUMPIFNULL
);
5881 testcase( pExpr
->op
==TK_IS
);
5882 testcase( pExpr
->op
==TK_ISNOT
);
5883 op
= (pExpr
->op
==TK_IS
) ? TK_NE
: TK_EQ
;
5884 jumpIfNull
= SQLITE_NULLEQ
;
5885 /* no break */ deliberate_fall_through
5892 if( sqlite3ExprIsVector(pExpr
->pLeft
) ) goto default_expr
;
5893 testcase( jumpIfNull
==0 );
5894 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5895 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
5896 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
5897 r1
, r2
, dest
, jumpIfNull
,ExprHasProperty(pExpr
,EP_Commuted
));
5898 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
5899 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
5900 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
5901 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
5902 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
);
5903 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
!=SQLITE_NULLEQ
);
5904 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
==SQLITE_NULLEQ
);
5905 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
);
5906 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
!=SQLITE_NULLEQ
);
5907 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
==SQLITE_NULLEQ
);
5908 testcase( regFree1
==0 );
5909 testcase( regFree2
==0 );
5914 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5915 sqlite3VdbeTypeofColumn(v
, r1
);
5916 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
5917 testcase( op
==TK_ISNULL
); VdbeCoverageIf(v
, op
==TK_ISNULL
);
5918 testcase( op
==TK_NOTNULL
); VdbeCoverageIf(v
, op
==TK_NOTNULL
);
5919 testcase( regFree1
==0 );
5923 testcase( jumpIfNull
==0 );
5924 exprCodeBetween(pParse
, pExpr
, dest
, sqlite3ExprIfFalse
, jumpIfNull
);
5927 #ifndef SQLITE_OMIT_SUBQUERY
5930 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, dest
);
5932 int destIfNull
= sqlite3VdbeMakeLabel(pParse
);
5933 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, destIfNull
);
5934 sqlite3VdbeResolveLabel(v
, destIfNull
);
5941 if( ExprAlwaysFalse(pExpr
) ){
5942 sqlite3VdbeGoto(v
, dest
);
5943 }else if( ExprAlwaysTrue(pExpr
) ){
5946 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
5947 sqlite3VdbeAddOp3(v
, OP_IfNot
, r1
, dest
, jumpIfNull
!=0);
5949 testcase( regFree1
==0 );
5950 testcase( jumpIfNull
==0 );
5955 sqlite3ReleaseTempReg(pParse
, regFree1
);
5956 sqlite3ReleaseTempReg(pParse
, regFree2
);
5960 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5961 ** code generation, and that copy is deleted after code generation. This
5962 ** ensures that the original pExpr is unchanged.
5964 void sqlite3ExprIfFalseDup(Parse
*pParse
, Expr
*pExpr
, int dest
,int jumpIfNull
){
5965 sqlite3
*db
= pParse
->db
;
5966 Expr
*pCopy
= sqlite3ExprDup(db
, pExpr
, 0);
5967 if( db
->mallocFailed
==0 ){
5968 sqlite3ExprIfFalse(pParse
, pCopy
, dest
, jumpIfNull
);
5970 sqlite3ExprDelete(db
, pCopy
);
5974 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5975 ** type of expression.
5977 ** If pExpr is a simple SQL value - an integer, real, string, blob
5978 ** or NULL value - then the VDBE currently being prepared is configured
5979 ** to re-prepare each time a new value is bound to variable pVar.
5981 ** Additionally, if pExpr is a simple SQL value and the value is the
5982 ** same as that currently bound to variable pVar, non-zero is returned.
5983 ** Otherwise, if the values are not the same or if pExpr is not a simple
5984 ** SQL value, zero is returned.
5986 static int exprCompareVariable(
5987 const Parse
*pParse
,
5993 sqlite3_value
*pL
, *pR
= 0;
5995 sqlite3ValueFromExpr(pParse
->db
, pExpr
, SQLITE_UTF8
, SQLITE_AFF_BLOB
, &pR
);
5997 iVar
= pVar
->iColumn
;
5998 sqlite3VdbeSetVarmask(pParse
->pVdbe
, iVar
);
5999 pL
= sqlite3VdbeGetBoundValue(pParse
->pReprepare
, iVar
, SQLITE_AFF_BLOB
);
6001 if( sqlite3_value_type(pL
)==SQLITE_TEXT
){
6002 sqlite3_value_text(pL
); /* Make sure the encoding is UTF-8 */
6004 res
= 0==sqlite3MemCompare(pL
, pR
, 0);
6006 sqlite3ValueFree(pR
);
6007 sqlite3ValueFree(pL
);
6014 ** Do a deep comparison of two expression trees. Return 0 if the two
6015 ** expressions are completely identical. Return 1 if they differ only
6016 ** by a COLLATE operator at the top level. Return 2 if there are differences
6017 ** other than the top-level COLLATE operator.
6019 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6020 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6022 ** The pA side might be using TK_REGISTER. If that is the case and pB is
6023 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
6025 ** Sometimes this routine will return 2 even if the two expressions
6026 ** really are equivalent. If we cannot prove that the expressions are
6027 ** identical, we return 2 just to be safe. So if this routine
6028 ** returns 2, then you do not really know for certain if the two
6029 ** expressions are the same. But if you get a 0 or 1 return, then you
6030 ** can be sure the expressions are the same. In the places where
6031 ** this routine is used, it does not hurt to get an extra 2 - that
6032 ** just might result in some slightly slower code. But returning
6033 ** an incorrect 0 or 1 could lead to a malfunction.
6035 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
6036 ** pParse->pReprepare can be matched against literals in pB. The
6037 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
6038 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
6039 ** Argument pParse should normally be NULL. If it is not NULL and pA or
6040 ** pB causes a return value of 2.
6042 int sqlite3ExprCompare(
6043 const Parse
*pParse
,
6049 if( pA
==0 || pB
==0 ){
6050 return pB
==pA
? 0 : 2;
6052 if( pParse
&& pA
->op
==TK_VARIABLE
&& exprCompareVariable(pParse
, pA
, pB
) ){
6055 combinedFlags
= pA
->flags
| pB
->flags
;
6056 if( combinedFlags
& EP_IntValue
){
6057 if( (pA
->flags
&pB
->flags
&EP_IntValue
)!=0 && pA
->u
.iValue
==pB
->u
.iValue
){
6062 if( pA
->op
!=pB
->op
|| pA
->op
==TK_RAISE
){
6063 if( pA
->op
==TK_COLLATE
&& sqlite3ExprCompare(pParse
, pA
->pLeft
,pB
,iTab
)<2 ){
6066 if( pB
->op
==TK_COLLATE
&& sqlite3ExprCompare(pParse
, pA
,pB
->pLeft
,iTab
)<2 ){
6069 if( pA
->op
==TK_AGG_COLUMN
&& pB
->op
==TK_COLUMN
6070 && pB
->iTable
<0 && pA
->iTable
==iTab
6077 assert( !ExprHasProperty(pA
, EP_IntValue
) );
6078 assert( !ExprHasProperty(pB
, EP_IntValue
) );
6080 if( pA
->op
==TK_FUNCTION
|| pA
->op
==TK_AGG_FUNCTION
){
6081 if( sqlite3StrICmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ) return 2;
6082 #ifndef SQLITE_OMIT_WINDOWFUNC
6083 assert( pA
->op
==pB
->op
);
6084 if( ExprHasProperty(pA
,EP_WinFunc
)!=ExprHasProperty(pB
,EP_WinFunc
) ){
6087 if( ExprHasProperty(pA
,EP_WinFunc
) ){
6088 if( sqlite3WindowCompare(pParse
, pA
->y
.pWin
, pB
->y
.pWin
, 1)!=0 ){
6093 }else if( pA
->op
==TK_NULL
){
6095 }else if( pA
->op
==TK_COLLATE
){
6096 if( sqlite3_stricmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ) return 2;
6099 && pA
->op
!=TK_COLUMN
6100 && pA
->op
!=TK_AGG_COLUMN
6101 && strcmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0
6106 if( (pA
->flags
& (EP_Distinct
|EP_Commuted
))
6107 != (pB
->flags
& (EP_Distinct
|EP_Commuted
)) ) return 2;
6108 if( ALWAYS((combinedFlags
& EP_TokenOnly
)==0) ){
6109 if( combinedFlags
& EP_xIsSelect
) return 2;
6110 if( (combinedFlags
& EP_FixedCol
)==0
6111 && sqlite3ExprCompare(pParse
, pA
->pLeft
, pB
->pLeft
, iTab
) ) return 2;
6112 if( sqlite3ExprCompare(pParse
, pA
->pRight
, pB
->pRight
, iTab
) ) return 2;
6113 if( sqlite3ExprListCompare(pA
->x
.pList
, pB
->x
.pList
, iTab
) ) return 2;
6114 if( pA
->op
!=TK_STRING
6115 && pA
->op
!=TK_TRUEFALSE
6116 && ALWAYS((combinedFlags
& EP_Reduced
)==0)
6118 if( pA
->iColumn
!=pB
->iColumn
) return 2;
6119 if( pA
->op2
!=pB
->op2
&& pA
->op
==TK_TRUTH
) return 2;
6120 if( pA
->op
!=TK_IN
&& pA
->iTable
!=pB
->iTable
&& pA
->iTable
!=iTab
){
6129 ** Compare two ExprList objects. Return 0 if they are identical, 1
6130 ** if they are certainly different, or 2 if it is not possible to
6131 ** determine if they are identical or not.
6133 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6134 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6136 ** This routine might return non-zero for equivalent ExprLists. The
6137 ** only consequence will be disabled optimizations. But this routine
6138 ** must never return 0 if the two ExprList objects are different, or
6139 ** a malfunction will result.
6141 ** Two NULL pointers are considered to be the same. But a NULL pointer
6142 ** always differs from a non-NULL pointer.
6144 int sqlite3ExprListCompare(const ExprList
*pA
, const ExprList
*pB
, int iTab
){
6146 if( pA
==0 && pB
==0 ) return 0;
6147 if( pA
==0 || pB
==0 ) return 1;
6148 if( pA
->nExpr
!=pB
->nExpr
) return 1;
6149 for(i
=0; i
<pA
->nExpr
; i
++){
6151 Expr
*pExprA
= pA
->a
[i
].pExpr
;
6152 Expr
*pExprB
= pB
->a
[i
].pExpr
;
6153 if( pA
->a
[i
].fg
.sortFlags
!=pB
->a
[i
].fg
.sortFlags
) return 1;
6154 if( (res
= sqlite3ExprCompare(0, pExprA
, pExprB
, iTab
)) ) return res
;
6160 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
6163 int sqlite3ExprCompareSkip(Expr
*pA
,Expr
*pB
, int iTab
){
6164 return sqlite3ExprCompare(0,
6165 sqlite3ExprSkipCollate(pA
),
6166 sqlite3ExprSkipCollate(pB
),
6171 ** Return non-zero if Expr p can only be true if pNN is not NULL.
6173 ** Or if seenNot is true, return non-zero if Expr p can only be
6174 ** non-NULL if pNN is not NULL
6176 static int exprImpliesNotNull(
6177 const Parse
*pParse
,/* Parsing context */
6178 const Expr
*p
, /* The expression to be checked */
6179 const Expr
*pNN
, /* The expression that is NOT NULL */
6180 int iTab
, /* Table being evaluated */
6181 int seenNot
/* Return true only if p can be any non-NULL value */
6185 if( sqlite3ExprCompare(pParse
, p
, pNN
, iTab
)==0 ){
6186 return pNN
->op
!=TK_NULL
;
6190 if( seenNot
&& ExprHasProperty(p
, EP_xIsSelect
) ) return 0;
6191 assert( ExprUseXSelect(p
) || (p
->x
.pList
!=0 && p
->x
.pList
->nExpr
>0) );
6192 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6196 assert( ExprUseXList(p
) );
6199 assert( pList
->nExpr
==2 );
6200 if( seenNot
) return 0;
6201 if( exprImpliesNotNull(pParse
, pList
->a
[0].pExpr
, pNN
, iTab
, 1)
6202 || exprImpliesNotNull(pParse
, pList
->a
[1].pExpr
, pNN
, iTab
, 1)
6206 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6221 /* no break */ deliberate_fall_through
6226 if( exprImpliesNotNull(pParse
, p
->pRight
, pNN
, iTab
, seenNot
) ) return 1;
6227 /* no break */ deliberate_fall_through
6233 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, seenNot
);
6236 if( seenNot
) return 0;
6237 if( p
->op2
!=TK_IS
) return 0;
6238 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6242 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6249 ** Return true if we can prove the pE2 will always be true if pE1 is
6250 ** true. Return false if we cannot complete the proof or if pE2 might
6251 ** be false. Examples:
6253 ** pE1: x==5 pE2: x==5 Result: true
6254 ** pE1: x>0 pE2: x==5 Result: false
6255 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
6256 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
6257 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
6258 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
6259 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false
6261 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
6262 ** Expr.iTable<0 then assume a table number given by iTab.
6264 ** If pParse is not NULL, then the values of bound variables in pE1 are
6265 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
6266 ** modified to record which bound variables are referenced. If pParse
6267 ** is NULL, then false will be returned if pE1 contains any bound variables.
6269 ** When in doubt, return false. Returning true might give a performance
6270 ** improvement. Returning false might cause a performance reduction, but
6271 ** it will always give the correct answer and is hence always safe.
6273 int sqlite3ExprImpliesExpr(
6274 const Parse
*pParse
,
6279 if( sqlite3ExprCompare(pParse
, pE1
, pE2
, iTab
)==0 ){
6283 && (sqlite3ExprImpliesExpr(pParse
, pE1
, pE2
->pLeft
, iTab
)
6284 || sqlite3ExprImpliesExpr(pParse
, pE1
, pE2
->pRight
, iTab
) )
6288 if( pE2
->op
==TK_NOTNULL
6289 && exprImpliesNotNull(pParse
, pE1
, pE2
->pLeft
, iTab
, 0)
6296 /* This is a helper function to impliesNotNullRow(). In this routine,
6297 ** set pWalker->eCode to one only if *both* of the input expressions
6298 ** separately have the implies-not-null-row property.
6300 static void bothImplyNotNullRow(Walker
*pWalker
, Expr
*pE1
, Expr
*pE2
){
6301 if( pWalker
->eCode
==0 ){
6302 sqlite3WalkExpr(pWalker
, pE1
);
6303 if( pWalker
->eCode
){
6305 sqlite3WalkExpr(pWalker
, pE2
);
6311 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
6312 ** If the expression node requires that the table at pWalker->iCur
6313 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
6315 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
6316 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when
6317 ** evaluating terms in the ON clause of an inner join.
6319 ** This routine controls an optimization. False positives (setting
6320 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
6321 ** (never setting pWalker->eCode) is a harmless missed optimization.
6323 static int impliesNotNullRow(Walker
*pWalker
, Expr
*pExpr
){
6324 testcase( pExpr
->op
==TK_AGG_COLUMN
);
6325 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
6326 if( ExprHasProperty(pExpr
, EP_OuterON
) ) return WRC_Prune
;
6327 if( ExprHasProperty(pExpr
, EP_InnerON
) && pWalker
->mWFlags
){
6328 /* If iCur is used in an inner-join ON clause to the left of a
6329 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
6330 ** But it is difficult to check for that condition precisely.
6331 ** To keep things simple, any use of iCur from any inner-join is
6332 ** ignored while attempting to simplify a RIGHT JOIN. */
6335 switch( pExpr
->op
){
6344 testcase( pExpr
->op
==TK_ISNOT
);
6345 testcase( pExpr
->op
==TK_ISNULL
);
6346 testcase( pExpr
->op
==TK_NOTNULL
);
6347 testcase( pExpr
->op
==TK_IS
);
6348 testcase( pExpr
->op
==TK_VECTOR
);
6349 testcase( pExpr
->op
==TK_FUNCTION
);
6350 testcase( pExpr
->op
==TK_TRUTH
);
6351 testcase( pExpr
->op
==TK_CASE
);
6355 if( pWalker
->u
.iCur
==pExpr
->iTable
){
6363 /* Both sides of an AND or OR must separately imply non-null-row.
6364 ** Consider these cases:
6367 ** If only one of x or y is non-null-row, then the overall expression
6368 ** can be true if the other arm is false (case 1) or true (case 2).
6370 testcase( pExpr
->op
==TK_OR
);
6371 testcase( pExpr
->op
==TK_AND
);
6372 bothImplyNotNullRow(pWalker
, pExpr
->pLeft
, pExpr
->pRight
);
6376 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
6377 ** both of which can be true. But apart from these cases, if
6378 ** the left-hand side of the IN is NULL then the IN itself will be
6380 if( ExprUseXList(pExpr
) && ALWAYS(pExpr
->x
.pList
->nExpr
>0) ){
6381 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
6386 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
6387 ** both y and z must be non-null row */
6388 assert( ExprUseXList(pExpr
) );
6389 assert( pExpr
->x
.pList
->nExpr
==2 );
6390 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
6391 bothImplyNotNullRow(pWalker
, pExpr
->x
.pList
->a
[0].pExpr
,
6392 pExpr
->x
.pList
->a
[1].pExpr
);
6395 /* Virtual tables are allowed to use constraints like x=NULL. So
6396 ** a term of the form x=y does not prove that y is not null if x
6397 ** is the column of a virtual table */
6404 Expr
*pLeft
= pExpr
->pLeft
;
6405 Expr
*pRight
= pExpr
->pRight
;
6406 testcase( pExpr
->op
==TK_EQ
);
6407 testcase( pExpr
->op
==TK_NE
);
6408 testcase( pExpr
->op
==TK_LT
);
6409 testcase( pExpr
->op
==TK_LE
);
6410 testcase( pExpr
->op
==TK_GT
);
6411 testcase( pExpr
->op
==TK_GE
);
6412 /* The y.pTab=0 assignment in wherecode.c always happens after the
6413 ** impliesNotNullRow() test */
6414 assert( pLeft
->op
!=TK_COLUMN
|| ExprUseYTab(pLeft
) );
6415 assert( pRight
->op
!=TK_COLUMN
|| ExprUseYTab(pRight
) );
6416 if( (pLeft
->op
==TK_COLUMN
6417 && ALWAYS(pLeft
->y
.pTab
!=0)
6418 && IsVirtual(pLeft
->y
.pTab
))
6419 || (pRight
->op
==TK_COLUMN
6420 && ALWAYS(pRight
->y
.pTab
!=0)
6421 && IsVirtual(pRight
->y
.pTab
))
6425 /* no break */ deliberate_fall_through
6428 return WRC_Continue
;
6433 ** Return true (non-zero) if expression p can only be true if at least
6434 ** one column of table iTab is non-null. In other words, return true
6435 ** if expression p will always be NULL or false if every column of iTab
6438 ** False negatives are acceptable. In other words, it is ok to return
6439 ** zero even if expression p will never be true of every column of iTab
6440 ** is NULL. A false negative is merely a missed optimization opportunity.
6442 ** False positives are not allowed, however. A false positive may result
6443 ** in an incorrect answer.
6445 ** Terms of p that are marked with EP_OuterON (and hence that come from
6446 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6448 ** This routine is used to check if a LEFT JOIN can be converted into
6449 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6450 ** clause requires that some column of the right table of the LEFT JOIN
6451 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6454 int sqlite3ExprImpliesNonNullRow(Expr
*p
, int iTab
, int isRJ
){
6456 p
= sqlite3ExprSkipCollateAndLikely(p
);
6457 if( p
==0 ) return 0;
6458 if( p
->op
==TK_NOTNULL
){
6461 while( p
->op
==TK_AND
){
6462 if( sqlite3ExprImpliesNonNullRow(p
->pLeft
, iTab
, isRJ
) ) return 1;
6466 w
.xExprCallback
= impliesNotNullRow
;
6467 w
.xSelectCallback
= 0;
6468 w
.xSelectCallback2
= 0;
6470 w
.mWFlags
= isRJ
!=0;
6472 sqlite3WalkExpr(&w
, p
);
6477 ** An instance of the following structure is used by the tree walker
6478 ** to determine if an expression can be evaluated by reference to the
6479 ** index only, without having to do a search for the corresponding
6480 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6481 ** is the cursor for the table.
6484 Index
*pIdx
; /* The index to be tested for coverage */
6485 int iCur
; /* Cursor number for the table corresponding to the index */
6489 ** Check to see if there are references to columns in table
6490 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6491 ** pWalker->u.pIdxCover->pIdx.
6493 static int exprIdxCover(Walker
*pWalker
, Expr
*pExpr
){
6494 if( pExpr
->op
==TK_COLUMN
6495 && pExpr
->iTable
==pWalker
->u
.pIdxCover
->iCur
6496 && sqlite3TableColumnToIndex(pWalker
->u
.pIdxCover
->pIdx
, pExpr
->iColumn
)<0
6501 return WRC_Continue
;
6505 ** Determine if an index pIdx on table with cursor iCur contains will
6506 ** the expression pExpr. Return true if the index does cover the
6507 ** expression and false if the pExpr expression references table columns
6508 ** that are not found in the index pIdx.
6510 ** An index covering an expression means that the expression can be
6511 ** evaluated using only the index and without having to lookup the
6512 ** corresponding table entry.
6514 int sqlite3ExprCoveredByIndex(
6515 Expr
*pExpr
, /* The index to be tested */
6516 int iCur
, /* The cursor number for the corresponding table */
6517 Index
*pIdx
/* The index that might be used for coverage */
6520 struct IdxCover xcov
;
6521 memset(&w
, 0, sizeof(w
));
6524 w
.xExprCallback
= exprIdxCover
;
6525 w
.u
.pIdxCover
= &xcov
;
6526 sqlite3WalkExpr(&w
, pExpr
);
6531 /* Structure used to pass information throughout the Walker in order to
6532 ** implement sqlite3ReferencesSrcList().
6535 sqlite3
*db
; /* Database connection used for sqlite3DbRealloc() */
6536 SrcList
*pRef
; /* Looking for references to these tables */
6537 i64 nExclude
; /* Number of tables to exclude from the search */
6538 int *aiExclude
; /* Cursor IDs for tables to exclude from the search */
6542 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6544 ** When entering a new subquery on the pExpr argument, add all FROM clause
6545 ** entries for that subquery to the exclude list.
6547 ** When leaving the subquery, remove those entries from the exclude list.
6549 static int selectRefEnter(Walker
*pWalker
, Select
*pSelect
){
6550 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6551 SrcList
*pSrc
= pSelect
->pSrc
;
6554 if( pSrc
->nSrc
==0 ) return WRC_Continue
;
6556 p
->nExclude
+= pSrc
->nSrc
;
6557 piNew
= sqlite3DbRealloc(p
->db
, p
->aiExclude
, p
->nExclude
*sizeof(int));
6562 p
->aiExclude
= piNew
;
6564 for(i
=0; i
<pSrc
->nSrc
; i
++, j
++){
6565 p
->aiExclude
[j
] = pSrc
->a
[i
].iCursor
;
6567 return WRC_Continue
;
6569 static void selectRefLeave(Walker
*pWalker
, Select
*pSelect
){
6570 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6571 SrcList
*pSrc
= pSelect
->pSrc
;
6573 assert( p
->nExclude
>=pSrc
->nSrc
);
6574 p
->nExclude
-= pSrc
->nSrc
;
6578 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6580 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6581 ** of the tables shown in RefSrcList.pRef.
6583 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6584 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6586 static int exprRefToSrcList(Walker
*pWalker
, Expr
*pExpr
){
6587 if( pExpr
->op
==TK_COLUMN
6588 || pExpr
->op
==TK_AGG_COLUMN
6591 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6592 SrcList
*pSrc
= p
->pRef
;
6593 int nSrc
= pSrc
? pSrc
->nSrc
: 0;
6594 for(i
=0; i
<nSrc
; i
++){
6595 if( pExpr
->iTable
==pSrc
->a
[i
].iCursor
){
6596 pWalker
->eCode
|= 1;
6597 return WRC_Continue
;
6600 for(i
=0; i
<p
->nExclude
&& p
->aiExclude
[i
]!=pExpr
->iTable
; i
++){}
6601 if( i
>=p
->nExclude
){
6602 pWalker
->eCode
|= 2;
6605 return WRC_Continue
;
6609 ** Check to see if pExpr references any tables in pSrcList.
6610 ** Possible return values:
6612 ** 1 pExpr does references a table in pSrcList.
6614 ** 0 pExpr references some table that is not defined in either
6615 ** pSrcList or in subqueries of pExpr itself.
6617 ** -1 pExpr only references no tables at all, or it only
6618 ** references tables defined in subqueries of pExpr itself.
6620 ** As currently used, pExpr is always an aggregate function call. That
6621 ** fact is exploited for efficiency.
6623 int sqlite3ReferencesSrcList(Parse
*pParse
, Expr
*pExpr
, SrcList
*pSrcList
){
6625 struct RefSrcList x
;
6626 assert( pParse
->db
!=0 );
6627 memset(&w
, 0, sizeof(w
));
6628 memset(&x
, 0, sizeof(x
));
6629 w
.xExprCallback
= exprRefToSrcList
;
6630 w
.xSelectCallback
= selectRefEnter
;
6631 w
.xSelectCallback2
= selectRefLeave
;
6632 w
.u
.pRefSrcList
= &x
;
6635 assert( pExpr
->op
==TK_AGG_FUNCTION
);
6636 assert( ExprUseXList(pExpr
) );
6637 sqlite3WalkExprList(&w
, pExpr
->x
.pList
);
6639 assert( pExpr
->pLeft
->op
==TK_ORDER
);
6640 assert( ExprUseXList(pExpr
->pLeft
) );
6641 assert( pExpr
->pLeft
->x
.pList
!=0 );
6642 sqlite3WalkExprList(&w
, pExpr
->pLeft
->x
.pList
);
6644 #ifndef SQLITE_OMIT_WINDOWFUNC
6645 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
6646 sqlite3WalkExpr(&w
, pExpr
->y
.pWin
->pFilter
);
6649 if( x
.aiExclude
) sqlite3DbNNFreeNN(pParse
->db
, x
.aiExclude
);
6650 if( w
.eCode
& 0x01 ){
6652 }else if( w
.eCode
){
6660 ** This is a Walker expression node callback.
6662 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6663 ** object that is referenced does not refer directly to the Expr. If
6664 ** it does, make a copy. This is done because the pExpr argument is
6665 ** subject to change.
6667 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6668 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6670 static int agginfoPersistExprCb(Walker
*pWalker
, Expr
*pExpr
){
6671 if( ALWAYS(!ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
))
6672 && pExpr
->pAggInfo
!=0
6674 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
6675 int iAgg
= pExpr
->iAgg
;
6676 Parse
*pParse
= pWalker
->pParse
;
6677 sqlite3
*db
= pParse
->db
;
6679 if( pExpr
->op
!=TK_AGG_FUNCTION
){
6680 if( iAgg
<pAggInfo
->nColumn
6681 && pAggInfo
->aCol
[iAgg
].pCExpr
==pExpr
6683 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
6684 if( pExpr
&& !sqlite3ExprDeferredDelete(pParse
, pExpr
) ){
6685 pAggInfo
->aCol
[iAgg
].pCExpr
= pExpr
;
6689 assert( pExpr
->op
==TK_AGG_FUNCTION
);
6690 if( ALWAYS(iAgg
<pAggInfo
->nFunc
)
6691 && pAggInfo
->aFunc
[iAgg
].pFExpr
==pExpr
6693 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
6694 if( pExpr
&& !sqlite3ExprDeferredDelete(pParse
, pExpr
) ){
6695 pAggInfo
->aFunc
[iAgg
].pFExpr
= pExpr
;
6700 return WRC_Continue
;
6704 ** Initialize a Walker object so that will persist AggInfo entries referenced
6705 ** by the tree that is walked.
6707 void sqlite3AggInfoPersistWalkerInit(Walker
*pWalker
, Parse
*pParse
){
6708 memset(pWalker
, 0, sizeof(*pWalker
));
6709 pWalker
->pParse
= pParse
;
6710 pWalker
->xExprCallback
= agginfoPersistExprCb
;
6711 pWalker
->xSelectCallback
= sqlite3SelectWalkNoop
;
6715 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6716 ** the new element. Return a negative number if malloc fails.
6718 static int addAggInfoColumn(sqlite3
*db
, AggInfo
*pInfo
){
6720 pInfo
->aCol
= sqlite3ArrayAllocate(
6723 sizeof(pInfo
->aCol
[0]),
6731 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6732 ** the new element. Return a negative number if malloc fails.
6734 static int addAggInfoFunc(sqlite3
*db
, AggInfo
*pInfo
){
6736 pInfo
->aFunc
= sqlite3ArrayAllocate(
6739 sizeof(pInfo
->aFunc
[0]),
6747 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6748 ** Return the index in aCol[] of the entry that describes that column.
6750 ** If no prior entry is found, create a new one and return -1. The
6751 ** new column will have an index of pAggInfo->nColumn-1.
6753 static void findOrCreateAggInfoColumn(
6754 Parse
*pParse
, /* Parsing context */
6755 AggInfo
*pAggInfo
, /* The AggInfo object to search and/or modify */
6756 Expr
*pExpr
/* Expr describing the column to find or insert */
6758 struct AggInfo_col
*pCol
;
6761 assert( pAggInfo
->iFirstReg
==0 );
6762 pCol
= pAggInfo
->aCol
;
6763 for(k
=0; k
<pAggInfo
->nColumn
; k
++, pCol
++){
6764 if( pCol
->pCExpr
==pExpr
) return;
6765 if( pCol
->iTable
==pExpr
->iTable
6766 && pCol
->iColumn
==pExpr
->iColumn
6767 && pExpr
->op
!=TK_IF_NULL_ROW
6772 k
= addAggInfoColumn(pParse
->db
, pAggInfo
);
6775 assert( pParse
->db
->mallocFailed
);
6778 pCol
= &pAggInfo
->aCol
[k
];
6779 assert( ExprUseYTab(pExpr
) );
6780 pCol
->pTab
= pExpr
->y
.pTab
;
6781 pCol
->iTable
= pExpr
->iTable
;
6782 pCol
->iColumn
= pExpr
->iColumn
;
6783 pCol
->iSorterColumn
= -1;
6784 pCol
->pCExpr
= pExpr
;
6785 if( pAggInfo
->pGroupBy
&& pExpr
->op
!=TK_IF_NULL_ROW
){
6787 ExprList
*pGB
= pAggInfo
->pGroupBy
;
6788 struct ExprList_item
*pTerm
= pGB
->a
;
6790 for(j
=0; j
<n
; j
++, pTerm
++){
6791 Expr
*pE
= pTerm
->pExpr
;
6792 if( pE
->op
==TK_COLUMN
6793 && pE
->iTable
==pExpr
->iTable
6794 && pE
->iColumn
==pExpr
->iColumn
6796 pCol
->iSorterColumn
= j
;
6801 if( pCol
->iSorterColumn
<0 ){
6802 pCol
->iSorterColumn
= pAggInfo
->nSortingColumn
++;
6805 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
6806 assert( pExpr
->pAggInfo
==0 || pExpr
->pAggInfo
==pAggInfo
);
6807 pExpr
->pAggInfo
= pAggInfo
;
6808 if( pExpr
->op
==TK_COLUMN
){
6809 pExpr
->op
= TK_AGG_COLUMN
;
6811 pExpr
->iAgg
= (i16
)k
;
6815 ** This is the xExprCallback for a tree walker. It is used to
6816 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
6817 ** for additional information.
6819 static int analyzeAggregate(Walker
*pWalker
, Expr
*pExpr
){
6821 NameContext
*pNC
= pWalker
->u
.pNC
;
6822 Parse
*pParse
= pNC
->pParse
;
6823 SrcList
*pSrcList
= pNC
->pSrcList
;
6824 AggInfo
*pAggInfo
= pNC
->uNC
.pAggInfo
;
6826 assert( pNC
->ncFlags
& NC_UAggInfo
);
6827 assert( pAggInfo
->iFirstReg
==0 );
6828 switch( pExpr
->op
){
6832 assert( pParse
->iSelfTab
==0 );
6833 if( (pNC
->ncFlags
& NC_InAggFunc
)==0 ) break;
6834 if( pParse
->pIdxEpr
==0 ) break;
6835 for(pIEpr
=pParse
->pIdxEpr
; pIEpr
; pIEpr
=pIEpr
->pIENext
){
6836 int iDataCur
= pIEpr
->iDataCur
;
6837 if( iDataCur
<0 ) continue;
6838 if( sqlite3ExprCompare(0, pExpr
, pIEpr
->pExpr
, iDataCur
)==0 ) break;
6840 if( pIEpr
==0 ) break;
6841 if( NEVER(!ExprUseYTab(pExpr
)) ) break;
6842 for(i
=0; i
<pSrcList
->nSrc
; i
++){
6843 if( pSrcList
->a
[0].iCursor
==pIEpr
->iDataCur
) break;
6845 if( i
>=pSrcList
->nSrc
) break;
6846 if( NEVER(pExpr
->pAggInfo
!=0) ) break; /* Resolved by outer context */
6847 if( pParse
->nErr
){ return WRC_Abort
; }
6849 /* If we reach this point, it means that expression pExpr can be
6850 ** translated into a reference to an index column as described by
6853 memset(&tmp
, 0, sizeof(tmp
));
6854 tmp
.op
= TK_AGG_COLUMN
;
6855 tmp
.iTable
= pIEpr
->iIdxCur
;
6856 tmp
.iColumn
= pIEpr
->iIdxCol
;
6857 findOrCreateAggInfoColumn(pParse
, pAggInfo
, &tmp
);
6858 if( pParse
->nErr
){ return WRC_Abort
; }
6859 assert( pAggInfo
->aCol
!=0 );
6860 assert( tmp
.iAgg
<pAggInfo
->nColumn
);
6861 pAggInfo
->aCol
[tmp
.iAgg
].pCExpr
= pExpr
;
6862 pExpr
->pAggInfo
= pAggInfo
;
6863 pExpr
->iAgg
= tmp
.iAgg
;
6866 case TK_IF_NULL_ROW
:
6869 testcase( pExpr
->op
==TK_AGG_COLUMN
);
6870 testcase( pExpr
->op
==TK_COLUMN
);
6871 testcase( pExpr
->op
==TK_IF_NULL_ROW
);
6872 /* Check to see if the column is in one of the tables in the FROM
6873 ** clause of the aggregate query */
6874 if( ALWAYS(pSrcList
!=0) ){
6875 SrcItem
*pItem
= pSrcList
->a
;
6876 for(i
=0; i
<pSrcList
->nSrc
; i
++, pItem
++){
6877 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
6878 if( pExpr
->iTable
==pItem
->iCursor
){
6879 findOrCreateAggInfoColumn(pParse
, pAggInfo
, pExpr
);
6881 } /* endif pExpr->iTable==pItem->iCursor */
6882 } /* end loop over pSrcList */
6884 return WRC_Continue
;
6886 case TK_AGG_FUNCTION
: {
6887 if( (pNC
->ncFlags
& NC_InAggFunc
)==0
6888 && pWalker
->walkerDepth
==pExpr
->op2
6889 && pExpr
->pAggInfo
==0
6891 /* Check to see if pExpr is a duplicate of another aggregate
6892 ** function that is already in the pAggInfo structure
6894 struct AggInfo_func
*pItem
= pAggInfo
->aFunc
;
6895 for(i
=0; i
<pAggInfo
->nFunc
; i
++, pItem
++){
6896 if( NEVER(pItem
->pFExpr
==pExpr
) ) break;
6897 if( sqlite3ExprCompare(0, pItem
->pFExpr
, pExpr
, -1)==0 ){
6901 if( i
>=pAggInfo
->nFunc
){
6902 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
6904 u8 enc
= ENC(pParse
->db
);
6905 i
= addAggInfoFunc(pParse
->db
, pAggInfo
);
6908 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
6909 pItem
= &pAggInfo
->aFunc
[i
];
6910 pItem
->pFExpr
= pExpr
;
6911 assert( ExprUseUToken(pExpr
) );
6912 nArg
= pExpr
->x
.pList
? pExpr
->x
.pList
->nExpr
: 0;
6913 pItem
->pFunc
= sqlite3FindFunction(pParse
->db
,
6914 pExpr
->u
.zToken
, nArg
, enc
, 0);
6915 assert( pItem
->bOBUnique
==0 );
6917 && (pItem
->pFunc
->funcFlags
& SQLITE_FUNC_NEEDCOLL
)==0
6919 /* The NEEDCOLL test above causes any ORDER BY clause on
6920 ** aggregate min() or max() to be ignored. */
6923 assert( pExpr
->pLeft
->op
==TK_ORDER
);
6924 assert( ExprUseXList(pExpr
->pLeft
) );
6925 pItem
->iOBTab
= pParse
->nTab
++;
6926 pOBList
= pExpr
->pLeft
->x
.pList
;
6927 assert( pOBList
->nExpr
>0 );
6928 assert( pItem
->bOBUnique
==0 );
6929 if( pOBList
->nExpr
==1
6931 && sqlite3ExprCompare(0,pOBList
->a
[0].pExpr
,
6932 pExpr
->x
.pList
->a
[0].pExpr
,0)==0
6934 pItem
->bOBPayload
= 0;
6935 pItem
->bOBUnique
= ExprHasProperty(pExpr
, EP_Distinct
);
6937 pItem
->bOBPayload
= 1;
6939 pItem
->bUseSubtype
=
6940 (pItem
->pFunc
->funcFlags
& SQLITE_SUBTYPE
)!=0;
6944 if( ExprHasProperty(pExpr
, EP_Distinct
) && !pItem
->bOBUnique
){
6945 pItem
->iDistinct
= pParse
->nTab
++;
6947 pItem
->iDistinct
= -1;
6951 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6953 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
6954 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
6955 pExpr
->iAgg
= (i16
)i
;
6956 pExpr
->pAggInfo
= pAggInfo
;
6959 return WRC_Continue
;
6963 return WRC_Continue
;
6967 ** Analyze the pExpr expression looking for aggregate functions and
6968 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6969 ** points to. Additional entries are made on the AggInfo object as
6972 ** This routine should only be called after the expression has been
6973 ** analyzed by sqlite3ResolveExprNames().
6975 void sqlite3ExprAnalyzeAggregates(NameContext
*pNC
, Expr
*pExpr
){
6977 w
.xExprCallback
= analyzeAggregate
;
6978 w
.xSelectCallback
= sqlite3WalkerDepthIncrease
;
6979 w
.xSelectCallback2
= sqlite3WalkerDepthDecrease
;
6983 assert( pNC
->pSrcList
!=0 );
6984 sqlite3WalkExpr(&w
, pExpr
);
6988 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
6989 ** expression list. Return the number of errors.
6991 ** If an error is found, the analysis is cut short.
6993 void sqlite3ExprAnalyzeAggList(NameContext
*pNC
, ExprList
*pList
){
6994 struct ExprList_item
*pItem
;
6997 for(pItem
=pList
->a
, i
=0; i
<pList
->nExpr
; i
++, pItem
++){
6998 sqlite3ExprAnalyzeAggregates(pNC
, pItem
->pExpr
);
7004 ** Allocate a single new register for use to hold some intermediate result.
7006 int sqlite3GetTempReg(Parse
*pParse
){
7007 if( pParse
->nTempReg
==0 ){
7008 return ++pParse
->nMem
;
7010 return pParse
->aTempReg
[--pParse
->nTempReg
];
7014 ** Deallocate a register, making available for reuse for some other
7017 void sqlite3ReleaseTempReg(Parse
*pParse
, int iReg
){
7019 sqlite3VdbeReleaseRegisters(pParse
, iReg
, 1, 0, 0);
7020 if( pParse
->nTempReg
<ArraySize(pParse
->aTempReg
) ){
7021 pParse
->aTempReg
[pParse
->nTempReg
++] = iReg
;
7027 ** Allocate or deallocate a block of nReg consecutive registers.
7029 int sqlite3GetTempRange(Parse
*pParse
, int nReg
){
7031 if( nReg
==1 ) return sqlite3GetTempReg(pParse
);
7032 i
= pParse
->iRangeReg
;
7033 n
= pParse
->nRangeReg
;
7035 pParse
->iRangeReg
+= nReg
;
7036 pParse
->nRangeReg
-= nReg
;
7039 pParse
->nMem
+= nReg
;
7043 void sqlite3ReleaseTempRange(Parse
*pParse
, int iReg
, int nReg
){
7045 sqlite3ReleaseTempReg(pParse
, iReg
);
7048 sqlite3VdbeReleaseRegisters(pParse
, iReg
, nReg
, 0, 0);
7049 if( nReg
>pParse
->nRangeReg
){
7050 pParse
->nRangeReg
= nReg
;
7051 pParse
->iRangeReg
= iReg
;
7056 ** Mark all temporary registers as being unavailable for reuse.
7058 ** Always invoke this procedure after coding a subroutine or co-routine
7059 ** that might be invoked from other parts of the code, to ensure that
7060 ** the sub/co-routine does not use registers in common with the code that
7061 ** invokes the sub/co-routine.
7063 void sqlite3ClearTempRegCache(Parse
*pParse
){
7064 pParse
->nTempReg
= 0;
7065 pParse
->nRangeReg
= 0;
7069 ** Make sure sufficient registers have been allocated so that
7070 ** iReg is a valid register number.
7072 void sqlite3TouchRegister(Parse
*pParse
, int iReg
){
7073 if( pParse
->nMem
<iReg
) pParse
->nMem
= iReg
;
7076 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
7078 ** Return the latest reusable register in the set of all registers.
7079 ** The value returned is no less than iMin. If any register iMin or
7080 ** greater is in permanent use, then return one more than that last
7081 ** permanent register.
7083 int sqlite3FirstAvailableRegister(Parse
*pParse
, int iMin
){
7084 const ExprList
*pList
= pParse
->pConstExpr
;
7087 for(i
=0; i
<pList
->nExpr
; i
++){
7088 if( pList
->a
[i
].u
.iConstExprReg
>=iMin
){
7089 iMin
= pList
->a
[i
].u
.iConstExprReg
+ 1;
7093 pParse
->nTempReg
= 0;
7094 pParse
->nRangeReg
= 0;
7097 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
7100 ** Validate that no temporary register falls within the range of
7101 ** iFirst..iLast, inclusive. This routine is only call from within assert()
7105 int sqlite3NoTempsInRange(Parse
*pParse
, int iFirst
, int iLast
){
7107 if( pParse
->nRangeReg
>0
7108 && pParse
->iRangeReg
+pParse
->nRangeReg
> iFirst
7109 && pParse
->iRangeReg
<= iLast
7113 for(i
=0; i
<pParse
->nTempReg
; i
++){
7114 if( pParse
->aTempReg
[i
]>=iFirst
&& pParse
->aTempReg
[i
]<=iLast
){
7118 if( pParse
->pConstExpr
){
7119 ExprList
*pList
= pParse
->pConstExpr
;
7120 for(i
=0; i
<pList
->nExpr
; i
++){
7121 int iReg
= pList
->a
[i
].u
.iConstExprReg
;
7122 if( iReg
==0 ) continue;
7123 if( iReg
>=iFirst
&& iReg
<=iLast
) return 0;
7128 #endif /* SQLITE_DEBUG */