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
->iTable
==pExpr
->pLeft
->x
.pSelect
->pEList
->nExpr
);
71 return sqlite3ExprAffinity(
72 pExpr
->pLeft
->x
.pSelect
->pEList
->a
[pExpr
->iColumn
].pExpr
76 assert( ExprUseXList(pExpr
) );
77 return sqlite3ExprAffinity(pExpr
->x
.pList
->a
[0].pExpr
);
79 if( ExprHasProperty(pExpr
, EP_Skip
|EP_IfNullRow
) ){
80 assert( pExpr
->op
==TK_COLLATE
81 || pExpr
->op
==TK_IF_NULL_ROW
82 || (pExpr
->op
==TK_REGISTER
&& pExpr
->op2
==TK_IF_NULL_ROW
) );
87 if( op
!=TK_REGISTER
|| (op
= pExpr
->op2
)==TK_REGISTER
) break;
89 return pExpr
->affExpr
;
93 ** Make a guess at all the possible datatypes of the result that could
94 ** be returned by an expression. Return a bitmask indicating the answer:
100 ** If the expression must return NULL, then 0x00 is returned.
102 int sqlite3ExprDataType(const Expr
*pExpr
){
108 pExpr
= pExpr
->pLeft
;
125 case TK_AGG_FUNCTION
:
133 case TK_SELECT_COLUMN
:
135 int aff
= sqlite3ExprAffinity(pExpr
);
136 if( aff
>=SQLITE_AFF_NUMERIC
) return 0x05;
137 if( aff
==SQLITE_AFF_TEXT
) return 0x06;
143 ExprList
*pList
= pExpr
->x
.pList
;
144 assert( ExprUseXList(pExpr
) && pList
!=0 );
145 assert( pList
->nExpr
> 0);
146 for(ii
=1; ii
<pList
->nExpr
; ii
+=2){
147 res
|= sqlite3ExprDataType(pList
->a
[ii
].pExpr
);
149 if( pList
->nExpr
% 2 ){
150 res
|= sqlite3ExprDataType(pList
->a
[pList
->nExpr
-1].pExpr
);
157 } /* End of switch(op) */
158 } /* End of while(pExpr) */
163 ** Set the collating sequence for expression pExpr to be the collating
164 ** sequence named by pToken. Return a pointer to a new Expr node that
165 ** implements the COLLATE operator.
167 ** If a memory allocation error occurs, that fact is recorded in pParse->db
168 ** and the pExpr parameter is returned unchanged.
170 Expr
*sqlite3ExprAddCollateToken(
171 const Parse
*pParse
, /* Parsing context */
172 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
173 const Token
*pCollName
, /* Name of collating sequence */
174 int dequote
/* True to dequote pCollName */
176 if( pCollName
->n
>0 ){
177 Expr
*pNew
= sqlite3ExprAlloc(pParse
->db
, TK_COLLATE
, pCollName
, dequote
);
180 pNew
->flags
|= EP_Collate
|EP_Skip
;
186 Expr
*sqlite3ExprAddCollateString(
187 const Parse
*pParse
, /* Parsing context */
188 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
189 const char *zC
/* The collating sequence name */
193 sqlite3TokenInit(&s
, (char*)zC
);
194 return sqlite3ExprAddCollateToken(pParse
, pExpr
, &s
, 0);
198 ** Skip over any TK_COLLATE operators.
200 Expr
*sqlite3ExprSkipCollate(Expr
*pExpr
){
201 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
) ){
202 assert( pExpr
->op
==TK_COLLATE
);
203 pExpr
= pExpr
->pLeft
;
209 ** Skip over any TK_COLLATE operators and/or any unlikely()
210 ** or likelihood() or likely() functions at the root of an
213 Expr
*sqlite3ExprSkipCollateAndLikely(Expr
*pExpr
){
214 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
|EP_Unlikely
) ){
215 if( ExprHasProperty(pExpr
, EP_Unlikely
) ){
216 assert( ExprUseXList(pExpr
) );
217 assert( pExpr
->x
.pList
->nExpr
>0 );
218 assert( pExpr
->op
==TK_FUNCTION
);
219 pExpr
= pExpr
->x
.pList
->a
[0].pExpr
;
221 assert( pExpr
->op
==TK_COLLATE
);
222 pExpr
= pExpr
->pLeft
;
229 ** Return the collation sequence for the expression pExpr. If
230 ** there is no defined collating sequence, return NULL.
232 ** See also: sqlite3ExprNNCollSeq()
234 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
235 ** default collation if pExpr has no defined collation.
237 ** The collating sequence might be determined by a COLLATE operator
238 ** or by the presence of a column with a defined collating sequence.
239 ** COLLATE operators take first precedence. Left operands take
240 ** precedence over right operands.
242 CollSeq
*sqlite3ExprCollSeq(Parse
*pParse
, const Expr
*pExpr
){
243 sqlite3
*db
= pParse
->db
;
245 const Expr
*p
= pExpr
;
248 if( op
==TK_REGISTER
) op
= p
->op2
;
249 if( (op
==TK_AGG_COLUMN
&& p
->y
.pTab
!=0)
250 || op
==TK_COLUMN
|| op
==TK_TRIGGER
253 assert( ExprUseYTab(p
) );
254 assert( p
->y
.pTab
!=0 );
255 if( (j
= p
->iColumn
)>=0 ){
256 const char *zColl
= sqlite3ColumnColl(&p
->y
.pTab
->aCol
[j
]);
257 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
261 if( op
==TK_CAST
|| op
==TK_UPLUS
){
266 assert( ExprUseXList(p
) );
267 p
= p
->x
.pList
->a
[0].pExpr
;
270 if( op
==TK_COLLATE
){
271 assert( !ExprHasProperty(p
, EP_IntValue
) );
272 pColl
= sqlite3GetCollSeq(pParse
, ENC(db
), 0, p
->u
.zToken
);
275 if( p
->flags
& EP_Collate
){
276 if( p
->pLeft
&& (p
->pLeft
->flags
& EP_Collate
)!=0 ){
279 Expr
*pNext
= p
->pRight
;
280 /* The Expr.x union is never used at the same time as Expr.pRight */
281 assert( ExprUseXList(p
) );
282 assert( p
->x
.pList
==0 || p
->pRight
==0 );
283 if( p
->x
.pList
!=0 && !db
->mallocFailed
){
285 for(i
=0; ALWAYS(i
<p
->x
.pList
->nExpr
); i
++){
286 if( ExprHasProperty(p
->x
.pList
->a
[i
].pExpr
, EP_Collate
) ){
287 pNext
= p
->x
.pList
->a
[i
].pExpr
;
298 if( sqlite3CheckCollSeq(pParse
, pColl
) ){
305 ** Return the collation sequence for the expression pExpr. If
306 ** there is no defined collating sequence, return a pointer to the
307 ** defautl collation sequence.
309 ** See also: sqlite3ExprCollSeq()
311 ** The sqlite3ExprCollSeq() routine works the same except that it
312 ** returns NULL if there is no defined collation.
314 CollSeq
*sqlite3ExprNNCollSeq(Parse
*pParse
, const Expr
*pExpr
){
315 CollSeq
*p
= sqlite3ExprCollSeq(pParse
, pExpr
);
316 if( p
==0 ) p
= pParse
->db
->pDfltColl
;
322 ** Return TRUE if the two expressions have equivalent collating sequences.
324 int sqlite3ExprCollSeqMatch(Parse
*pParse
, const Expr
*pE1
, const Expr
*pE2
){
325 CollSeq
*pColl1
= sqlite3ExprNNCollSeq(pParse
, pE1
);
326 CollSeq
*pColl2
= sqlite3ExprNNCollSeq(pParse
, pE2
);
327 return sqlite3StrICmp(pColl1
->zName
, pColl2
->zName
)==0;
331 ** pExpr is an operand of a comparison operator. aff2 is the
332 ** type affinity of the other operand. This routine returns the
333 ** type affinity that should be used for the comparison operator.
335 char sqlite3CompareAffinity(const Expr
*pExpr
, char aff2
){
336 char aff1
= sqlite3ExprAffinity(pExpr
);
337 if( aff1
>SQLITE_AFF_NONE
&& aff2
>SQLITE_AFF_NONE
){
338 /* Both sides of the comparison are columns. If one has numeric
339 ** affinity, use that. Otherwise use no affinity.
341 if( sqlite3IsNumericAffinity(aff1
) || sqlite3IsNumericAffinity(aff2
) ){
342 return SQLITE_AFF_NUMERIC
;
344 return SQLITE_AFF_BLOB
;
347 /* One side is a column, the other is not. Use the columns affinity. */
348 assert( aff1
<=SQLITE_AFF_NONE
|| aff2
<=SQLITE_AFF_NONE
);
349 return (aff1
<=SQLITE_AFF_NONE
? aff2
: aff1
) | SQLITE_AFF_NONE
;
354 ** pExpr is a comparison operator. Return the type affinity that should
355 ** be applied to both operands prior to doing the comparison.
357 static char comparisonAffinity(const Expr
*pExpr
){
359 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_IN
|| pExpr
->op
==TK_LT
||
360 pExpr
->op
==TK_GT
|| pExpr
->op
==TK_GE
|| pExpr
->op
==TK_LE
||
361 pExpr
->op
==TK_NE
|| pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
);
362 assert( pExpr
->pLeft
);
363 aff
= sqlite3ExprAffinity(pExpr
->pLeft
);
365 aff
= sqlite3CompareAffinity(pExpr
->pRight
, aff
);
366 }else if( ExprUseXSelect(pExpr
) ){
367 aff
= sqlite3CompareAffinity(pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
, aff
);
369 aff
= SQLITE_AFF_BLOB
;
375 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
376 ** idx_affinity is the affinity of an indexed column. Return true
377 ** if the index with affinity idx_affinity may be used to implement
378 ** the comparison in pExpr.
380 int sqlite3IndexAffinityOk(const Expr
*pExpr
, char idx_affinity
){
381 char aff
= comparisonAffinity(pExpr
);
382 if( aff
<SQLITE_AFF_TEXT
){
385 if( aff
==SQLITE_AFF_TEXT
){
386 return idx_affinity
==SQLITE_AFF_TEXT
;
388 return sqlite3IsNumericAffinity(idx_affinity
);
392 ** Return the P5 value that should be used for a binary comparison
393 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
395 static u8
binaryCompareP5(
396 const Expr
*pExpr1
, /* Left operand */
397 const Expr
*pExpr2
, /* Right operand */
398 int jumpIfNull
/* Extra flags added to P5 */
400 u8 aff
= (char)sqlite3ExprAffinity(pExpr2
);
401 aff
= (u8
)sqlite3CompareAffinity(pExpr1
, aff
) | (u8
)jumpIfNull
;
406 ** Return a pointer to the collation sequence that should be used by
407 ** a binary comparison operator comparing pLeft and pRight.
409 ** If the left hand expression has a collating sequence type, then it is
410 ** used. Otherwise the collation sequence for the right hand expression
411 ** is used, or the default (BINARY) if neither expression has a collating
414 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
415 ** it is not considered.
417 CollSeq
*sqlite3BinaryCompareCollSeq(
424 if( pLeft
->flags
& EP_Collate
){
425 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
426 }else if( pRight
&& (pRight
->flags
& EP_Collate
)!=0 ){
427 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
429 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
431 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
437 /* Expresssion p is a comparison operator. Return a collation sequence
438 ** appropriate for the comparison operator.
440 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
441 ** However, if the OP_Commuted flag is set, then the order of the operands
442 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
443 ** correct collating sequence is found.
445 CollSeq
*sqlite3ExprCompareCollSeq(Parse
*pParse
, const Expr
*p
){
446 if( ExprHasProperty(p
, EP_Commuted
) ){
447 return sqlite3BinaryCompareCollSeq(pParse
, p
->pRight
, p
->pLeft
);
449 return sqlite3BinaryCompareCollSeq(pParse
, p
->pLeft
, p
->pRight
);
454 ** Generate code for a comparison operator.
456 static int codeCompare(
457 Parse
*pParse
, /* The parsing (and code generating) context */
458 Expr
*pLeft
, /* The left operand */
459 Expr
*pRight
, /* The right operand */
460 int opcode
, /* The comparison opcode */
461 int in1
, int in2
, /* Register holding operands */
462 int dest
, /* Jump here if true. */
463 int jumpIfNull
, /* If true, jump if either operand is NULL */
464 int isCommuted
/* The comparison has been commuted */
470 if( pParse
->nErr
) return 0;
472 p4
= sqlite3BinaryCompareCollSeq(pParse
, pRight
, pLeft
);
474 p4
= sqlite3BinaryCompareCollSeq(pParse
, pLeft
, pRight
);
476 p5
= binaryCompareP5(pLeft
, pRight
, jumpIfNull
);
477 addr
= sqlite3VdbeAddOp4(pParse
->pVdbe
, opcode
, in2
, dest
, in1
,
478 (void*)p4
, P4_COLLSEQ
);
479 sqlite3VdbeChangeP5(pParse
->pVdbe
, (u8
)p5
);
484 ** Return true if expression pExpr is a vector, or false otherwise.
486 ** A vector is defined as any expression that results in two or more
487 ** columns of result. Every TK_VECTOR node is an vector because the
488 ** parser will not generate a TK_VECTOR with fewer than two entries.
489 ** But a TK_SELECT might be either a vector or a scalar. It is only
490 ** considered a vector if it has two or more result columns.
492 int sqlite3ExprIsVector(const Expr
*pExpr
){
493 return sqlite3ExprVectorSize(pExpr
)>1;
497 ** If the expression passed as the only argument is of type TK_VECTOR
498 ** return the number of expressions in the vector. Or, if the expression
499 ** is a sub-select, return the number of columns in the sub-select. For
500 ** any other type of expression, return 1.
502 int sqlite3ExprVectorSize(const Expr
*pExpr
){
504 if( op
==TK_REGISTER
) op
= pExpr
->op2
;
506 assert( ExprUseXList(pExpr
) );
507 return pExpr
->x
.pList
->nExpr
;
508 }else if( op
==TK_SELECT
){
509 assert( ExprUseXSelect(pExpr
) );
510 return pExpr
->x
.pSelect
->pEList
->nExpr
;
517 ** Return a pointer to a subexpression of pVector that is the i-th
518 ** column of the vector (numbered starting with 0). The caller must
519 ** ensure that i is within range.
521 ** If pVector is really a scalar (and "scalar" here includes subqueries
522 ** that return a single column!) then return pVector unmodified.
524 ** pVector retains ownership of the returned subexpression.
526 ** If the vector is a (SELECT ...) then the expression returned is
527 ** just the expression for the i-th term of the result set, and may
528 ** not be ready for evaluation because the table cursor has not yet
531 Expr
*sqlite3VectorFieldSubexpr(Expr
*pVector
, int i
){
532 assert( i
<sqlite3ExprVectorSize(pVector
) || pVector
->op
==TK_ERROR
);
533 if( sqlite3ExprIsVector(pVector
) ){
534 assert( pVector
->op2
==0 || pVector
->op
==TK_REGISTER
);
535 if( pVector
->op
==TK_SELECT
|| pVector
->op2
==TK_SELECT
){
536 assert( ExprUseXSelect(pVector
) );
537 return pVector
->x
.pSelect
->pEList
->a
[i
].pExpr
;
539 assert( ExprUseXList(pVector
) );
540 return pVector
->x
.pList
->a
[i
].pExpr
;
547 ** Compute and return a new Expr object which when passed to
548 ** sqlite3ExprCode() will generate all necessary code to compute
549 ** the iField-th column of the vector expression pVector.
551 ** It is ok for pVector to be a scalar (as long as iField==0).
552 ** In that case, this routine works like sqlite3ExprDup().
554 ** The caller owns the returned Expr object and is responsible for
555 ** ensuring that the returned value eventually gets freed.
557 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
558 ** then the returned object will reference pVector and so pVector must remain
559 ** valid for the life of the returned object. If pVector is a TK_VECTOR
560 ** or a scalar expression, then it can be deleted as soon as this routine
563 ** A trick to cause a TK_SELECT pVector to be deleted together with
564 ** the returned Expr object is to attach the pVector to the pRight field
565 ** of the returned TK_SELECT_COLUMN Expr object.
567 Expr
*sqlite3ExprForVectorField(
568 Parse
*pParse
, /* Parsing context */
569 Expr
*pVector
, /* The vector. List of expressions or a sub-SELECT */
570 int iField
, /* Which column of the vector to return */
571 int nField
/* Total number of columns in the vector */
574 if( pVector
->op
==TK_SELECT
){
575 assert( ExprUseXSelect(pVector
) );
576 /* The TK_SELECT_COLUMN Expr node:
578 ** pLeft: pVector containing TK_SELECT. Not deleted.
579 ** pRight: not used. But recursively deleted.
580 ** iColumn: Index of a column in pVector
581 ** iTable: 0 or the number of columns on the LHS of an assignment
582 ** pLeft->iTable: First in an array of register holding result, or 0
583 ** if the result is not yet computed.
585 ** sqlite3ExprDelete() specifically skips the recursive delete of
586 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
587 ** can be attached to pRight to cause this node to take ownership of
588 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
589 ** with the same pLeft pointer to the pVector, but only one of them
590 ** will own the pVector.
592 pRet
= sqlite3PExpr(pParse
, TK_SELECT_COLUMN
, 0, 0);
594 pRet
->iTable
= nField
;
595 pRet
->iColumn
= iField
;
596 pRet
->pLeft
= pVector
;
599 if( pVector
->op
==TK_VECTOR
){
601 assert( ExprUseXList(pVector
) );
602 ppVector
= &pVector
->x
.pList
->a
[iField
].pExpr
;
604 if( IN_RENAME_OBJECT
){
605 /* This must be a vector UPDATE inside a trigger */
610 pRet
= sqlite3ExprDup(pParse
->db
, pVector
, 0);
616 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
617 ** it. Return the register in which the result is stored (or, if the
618 ** sub-select returns more than one column, the first in an array
619 ** of registers in which the result is stored).
621 ** If pExpr is not a TK_SELECT expression, return 0.
623 static int exprCodeSubselect(Parse
*pParse
, Expr
*pExpr
){
625 #ifndef SQLITE_OMIT_SUBQUERY
626 if( pExpr
->op
==TK_SELECT
){
627 reg
= sqlite3CodeSubselect(pParse
, pExpr
);
634 ** Argument pVector points to a vector expression - either a TK_VECTOR
635 ** or TK_SELECT that returns more than one column. This function returns
636 ** the register number of a register that contains the value of
637 ** element iField of the vector.
639 ** If pVector is a TK_SELECT expression, then code for it must have
640 ** already been generated using the exprCodeSubselect() routine. In this
641 ** case parameter regSelect should be the first in an array of registers
642 ** containing the results of the sub-select.
644 ** If pVector is of type TK_VECTOR, then code for the requested field
645 ** is generated. In this case (*pRegFree) may be set to the number of
646 ** a temporary register to be freed by the caller before returning.
648 ** Before returning, output parameter (*ppExpr) is set to point to the
649 ** Expr object corresponding to element iElem of the vector.
651 static int exprVectorRegister(
652 Parse
*pParse
, /* Parse context */
653 Expr
*pVector
, /* Vector to extract element from */
654 int iField
, /* Field to extract from pVector */
655 int regSelect
, /* First in array of registers */
656 Expr
**ppExpr
, /* OUT: Expression element */
657 int *pRegFree
/* OUT: Temp register to free */
660 assert( op
==TK_VECTOR
|| op
==TK_REGISTER
|| op
==TK_SELECT
|| op
==TK_ERROR
);
661 if( op
==TK_REGISTER
){
662 *ppExpr
= sqlite3VectorFieldSubexpr(pVector
, iField
);
663 return pVector
->iTable
+iField
;
666 assert( ExprUseXSelect(pVector
) );
667 *ppExpr
= pVector
->x
.pSelect
->pEList
->a
[iField
].pExpr
;
668 return regSelect
+iField
;
671 assert( ExprUseXList(pVector
) );
672 *ppExpr
= pVector
->x
.pList
->a
[iField
].pExpr
;
673 return sqlite3ExprCodeTemp(pParse
, *ppExpr
, pRegFree
);
679 ** Expression pExpr is a comparison between two vector values. Compute
680 ** the result of the comparison (1, 0, or NULL) and write that
681 ** result into register dest.
683 ** The caller must satisfy the following preconditions:
685 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
686 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
687 ** otherwise: op==pExpr->op and p5==0
689 static void codeVectorCompare(
690 Parse
*pParse
, /* Code generator context */
691 Expr
*pExpr
, /* The comparison operation */
692 int dest
, /* Write results into this register */
693 u8 op
, /* Comparison operator */
694 u8 p5
/* SQLITE_NULLEQ or zero */
696 Vdbe
*v
= pParse
->pVdbe
;
697 Expr
*pLeft
= pExpr
->pLeft
;
698 Expr
*pRight
= pExpr
->pRight
;
699 int nLeft
= sqlite3ExprVectorSize(pLeft
);
705 int addrDone
= sqlite3VdbeMakeLabel(pParse
);
706 int isCommuted
= ExprHasProperty(pExpr
,EP_Commuted
);
708 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
709 if( pParse
->nErr
) return;
710 if( nLeft
!=sqlite3ExprVectorSize(pRight
) ){
711 sqlite3ErrorMsg(pParse
, "row value misused");
714 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_NE
715 || pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
716 || pExpr
->op
==TK_LT
|| pExpr
->op
==TK_GT
717 || pExpr
->op
==TK_LE
|| pExpr
->op
==TK_GE
719 assert( pExpr
->op
==op
|| (pExpr
->op
==TK_IS
&& op
==TK_EQ
)
720 || (pExpr
->op
==TK_ISNOT
&& op
==TK_NE
) );
721 assert( p5
==0 || pExpr
->op
!=op
);
722 assert( p5
==SQLITE_NULLEQ
|| pExpr
->op
==op
);
724 if( op
==TK_LE
) opx
= TK_LT
;
725 if( op
==TK_GE
) opx
= TK_GT
;
726 if( op
==TK_NE
) opx
= TK_EQ
;
728 regLeft
= exprCodeSubselect(pParse
, pLeft
);
729 regRight
= exprCodeSubselect(pParse
, pRight
);
731 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, dest
);
732 for(i
=0; 1 /*Loop exits by "break"*/; i
++){
733 int regFree1
= 0, regFree2
= 0;
734 Expr
*pL
= 0, *pR
= 0;
736 assert( i
>=0 && i
<nLeft
);
737 if( addrCmp
) sqlite3VdbeJumpHere(v
, addrCmp
);
738 r1
= exprVectorRegister(pParse
, pLeft
, i
, regLeft
, &pL
, ®Free1
);
739 r2
= exprVectorRegister(pParse
, pRight
, i
, regRight
, &pR
, ®Free2
);
740 addrCmp
= sqlite3VdbeCurrentAddr(v
);
741 codeCompare(pParse
, pL
, pR
, opx
, r1
, r2
, addrDone
, p5
, isCommuted
);
742 testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
743 testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
744 testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
745 testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
746 testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
747 testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
748 sqlite3ReleaseTempReg(pParse
, regFree1
);
749 sqlite3ReleaseTempReg(pParse
, regFree2
);
750 if( (opx
==TK_LT
|| opx
==TK_GT
) && i
<nLeft
-1 ){
751 addrCmp
= sqlite3VdbeAddOp0(v
, OP_ElseEq
);
752 testcase(opx
==TK_LT
); VdbeCoverageIf(v
,opx
==TK_LT
);
753 testcase(opx
==TK_GT
); VdbeCoverageIf(v
,opx
==TK_GT
);
755 if( p5
==SQLITE_NULLEQ
){
756 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
);
758 sqlite3VdbeAddOp3(v
, OP_ZeroOrNull
, r1
, dest
, r2
);
764 sqlite3VdbeAddOp2(v
, OP_NotNull
, dest
, addrDone
); VdbeCoverage(v
);
766 assert( op
==TK_LT
|| op
==TK_GT
|| op
==TK_LE
|| op
==TK_GE
);
767 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrDone
);
768 if( i
==nLeft
-2 ) opx
= op
;
771 sqlite3VdbeJumpHere(v
, addrCmp
);
772 sqlite3VdbeResolveLabel(v
, addrDone
);
774 sqlite3VdbeAddOp2(v
, OP_Not
, dest
, dest
);
778 #if SQLITE_MAX_EXPR_DEPTH>0
780 ** Check that argument nHeight is less than or equal to the maximum
781 ** expression depth allowed. If it is not, leave an error message in
784 int sqlite3ExprCheckHeight(Parse
*pParse
, int nHeight
){
786 int mxHeight
= pParse
->db
->aLimit
[SQLITE_LIMIT_EXPR_DEPTH
];
787 if( nHeight
>mxHeight
){
788 sqlite3ErrorMsg(pParse
,
789 "Expression tree is too large (maximum depth %d)", mxHeight
796 /* The following three functions, heightOfExpr(), heightOfExprList()
797 ** and heightOfSelect(), are used to determine the maximum height
798 ** of any expression tree referenced by the structure passed as the
801 ** If this maximum height is greater than the current value pointed
802 ** to by pnHeight, the second parameter, then set *pnHeight to that
805 static void heightOfExpr(const Expr
*p
, int *pnHeight
){
807 if( p
->nHeight
>*pnHeight
){
808 *pnHeight
= p
->nHeight
;
812 static void heightOfExprList(const ExprList
*p
, int *pnHeight
){
815 for(i
=0; i
<p
->nExpr
; i
++){
816 heightOfExpr(p
->a
[i
].pExpr
, pnHeight
);
820 static void heightOfSelect(const Select
*pSelect
, int *pnHeight
){
822 for(p
=pSelect
; p
; p
=p
->pPrior
){
823 heightOfExpr(p
->pWhere
, pnHeight
);
824 heightOfExpr(p
->pHaving
, pnHeight
);
825 heightOfExpr(p
->pLimit
, pnHeight
);
826 heightOfExprList(p
->pEList
, pnHeight
);
827 heightOfExprList(p
->pGroupBy
, pnHeight
);
828 heightOfExprList(p
->pOrderBy
, pnHeight
);
833 ** Set the Expr.nHeight variable in the structure passed as an
834 ** argument. An expression with no children, Expr.pList or
835 ** Expr.pSelect member has a height of 1. Any other expression
836 ** has a height equal to the maximum height of any other
837 ** referenced Expr plus one.
839 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
842 static void exprSetHeight(Expr
*p
){
843 int nHeight
= p
->pLeft
? p
->pLeft
->nHeight
: 0;
844 if( NEVER(p
->pRight
) && p
->pRight
->nHeight
>nHeight
){
845 nHeight
= p
->pRight
->nHeight
;
847 if( ExprUseXSelect(p
) ){
848 heightOfSelect(p
->x
.pSelect
, &nHeight
);
849 }else if( p
->x
.pList
){
850 heightOfExprList(p
->x
.pList
, &nHeight
);
851 p
->flags
|= EP_Propagate
& sqlite3ExprListFlags(p
->x
.pList
);
853 p
->nHeight
= nHeight
+ 1;
857 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
858 ** the height is greater than the maximum allowed expression depth,
859 ** leave an error in pParse.
861 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
864 void sqlite3ExprSetHeightAndFlags(Parse
*pParse
, Expr
*p
){
865 if( pParse
->nErr
) return;
867 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
871 ** Return the maximum height of any expression tree referenced
872 ** by the select statement passed as an argument.
874 int sqlite3SelectExprHeight(const Select
*p
){
876 heightOfSelect(p
, &nHeight
);
879 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
881 ** Propagate all EP_Propagate flags from the Expr.x.pList into
884 void sqlite3ExprSetHeightAndFlags(Parse
*pParse
, Expr
*p
){
885 if( pParse
->nErr
) return;
886 if( p
&& ExprUseXList(p
) && p
->x
.pList
){
887 p
->flags
|= EP_Propagate
& sqlite3ExprListFlags(p
->x
.pList
);
890 #define exprSetHeight(y)
891 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
894 ** This routine is the core allocator for Expr nodes.
896 ** Construct a new expression node and return a pointer to it. Memory
897 ** for this node and for the pToken argument is a single allocation
898 ** obtained from sqlite3DbMalloc(). The calling function
899 ** is responsible for making sure the node eventually gets freed.
901 ** If dequote is true, then the token (if it exists) is dequoted.
902 ** If dequote is false, no dequoting is performed. The deQuote
903 ** parameter is ignored if pToken is NULL or if the token does not
904 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
905 ** then the EP_DblQuoted flag is set on the expression node.
907 ** Special case: If op==TK_INTEGER and pToken points to a string that
908 ** can be translated into a 32-bit integer, then the token is not
909 ** stored in u.zToken. Instead, the integer values is written
910 ** into u.iValue and the EP_IntValue flag is set. No extra storage
911 ** is allocated to hold the integer text and the dequote flag is ignored.
913 Expr
*sqlite3ExprAlloc(
914 sqlite3
*db
, /* Handle for sqlite3DbMallocRawNN() */
915 int op
, /* Expression opcode */
916 const Token
*pToken
, /* Token argument. Might be NULL */
917 int dequote
/* True to dequote */
925 if( op
!=TK_INTEGER
|| pToken
->z
==0
926 || sqlite3GetInt32(pToken
->z
, &iValue
)==0 ){
927 nExtra
= pToken
->n
+1;
931 pNew
= sqlite3DbMallocRawNN(db
, sizeof(Expr
)+nExtra
);
933 memset(pNew
, 0, sizeof(Expr
));
938 pNew
->flags
|= EP_IntValue
|EP_Leaf
|(iValue
?EP_IsTrue
:EP_IsFalse
);
939 pNew
->u
.iValue
= iValue
;
941 pNew
->u
.zToken
= (char*)&pNew
[1];
942 assert( pToken
->z
!=0 || pToken
->n
==0 );
943 if( pToken
->n
) memcpy(pNew
->u
.zToken
, pToken
->z
, pToken
->n
);
944 pNew
->u
.zToken
[pToken
->n
] = 0;
945 if( dequote
&& sqlite3Isquote(pNew
->u
.zToken
[0]) ){
946 sqlite3DequoteExpr(pNew
);
950 #if SQLITE_MAX_EXPR_DEPTH>0
958 ** Allocate a new expression node from a zero-terminated token that has
959 ** already been dequoted.
962 sqlite3
*db
, /* Handle for sqlite3DbMallocZero() (may be null) */
963 int op
, /* Expression opcode */
964 const char *zToken
/* Token argument. Might be NULL */
968 x
.n
= sqlite3Strlen30(zToken
);
969 return sqlite3ExprAlloc(db
, op
, &x
, 0);
973 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
975 ** If pRoot==NULL that means that a memory allocation error has occurred.
976 ** In that case, delete the subtrees pLeft and pRight.
978 void sqlite3ExprAttachSubtrees(
985 assert( db
->mallocFailed
);
986 sqlite3ExprDelete(db
, pLeft
);
987 sqlite3ExprDelete(db
, pRight
);
989 assert( ExprUseXList(pRoot
) );
990 assert( pRoot
->x
.pSelect
==0 );
992 pRoot
->pRight
= pRight
;
993 pRoot
->flags
|= EP_Propagate
& pRight
->flags
;
994 #if SQLITE_MAX_EXPR_DEPTH>0
995 pRoot
->nHeight
= pRight
->nHeight
+1;
1001 pRoot
->pLeft
= pLeft
;
1002 pRoot
->flags
|= EP_Propagate
& pLeft
->flags
;
1003 #if SQLITE_MAX_EXPR_DEPTH>0
1004 if( pLeft
->nHeight
>=pRoot
->nHeight
){
1005 pRoot
->nHeight
= pLeft
->nHeight
+1;
1013 ** Allocate an Expr node which joins as many as two subtrees.
1015 ** One or both of the subtrees can be NULL. Return a pointer to the new
1016 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1017 ** free the subtrees and return NULL.
1020 Parse
*pParse
, /* Parsing context */
1021 int op
, /* Expression opcode */
1022 Expr
*pLeft
, /* Left operand */
1023 Expr
*pRight
/* Right operand */
1026 p
= sqlite3DbMallocRawNN(pParse
->db
, sizeof(Expr
));
1028 memset(p
, 0, sizeof(Expr
));
1031 sqlite3ExprAttachSubtrees(pParse
->db
, p
, pLeft
, pRight
);
1032 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
1034 sqlite3ExprDelete(pParse
->db
, pLeft
);
1035 sqlite3ExprDelete(pParse
->db
, pRight
);
1041 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1042 ** do a memory allocation failure) then delete the pSelect object.
1044 void sqlite3PExprAddSelect(Parse
*pParse
, Expr
*pExpr
, Select
*pSelect
){
1046 pExpr
->x
.pSelect
= pSelect
;
1047 ExprSetProperty(pExpr
, EP_xIsSelect
|EP_Subquery
);
1048 sqlite3ExprSetHeightAndFlags(pParse
, pExpr
);
1050 assert( pParse
->db
->mallocFailed
);
1051 sqlite3SelectDelete(pParse
->db
, pSelect
);
1056 ** Expression list pEList is a list of vector values. This function
1057 ** converts the contents of pEList to a VALUES(...) Select statement
1058 ** returning 1 row for each element of the list. For example, the
1061 ** ( (1,2), (3,4) (5,6) )
1063 ** is translated to the equivalent of:
1065 ** VALUES(1,2), (3,4), (5,6)
1067 ** Each of the vector values in pEList must contain exactly nElem terms.
1068 ** If a list element that is not a vector or does not contain nElem terms,
1069 ** an error message is left in pParse.
1071 ** This is used as part of processing IN(...) expressions with a list
1072 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1074 Select
*sqlite3ExprListToValues(Parse
*pParse
, int nElem
, ExprList
*pEList
){
1078 for(ii
=0; ii
<pEList
->nExpr
; ii
++){
1080 Expr
*pExpr
= pEList
->a
[ii
].pExpr
;
1082 if( pExpr
->op
==TK_VECTOR
){
1083 assert( ExprUseXList(pExpr
) );
1084 nExprElem
= pExpr
->x
.pList
->nExpr
;
1088 if( nExprElem
!=nElem
){
1089 sqlite3ErrorMsg(pParse
, "IN(...) element has %d term%s - expected %d",
1090 nExprElem
, nExprElem
>1?"s":"", nElem
1094 assert( ExprUseXList(pExpr
) );
1095 pSel
= sqlite3SelectNew(pParse
, pExpr
->x
.pList
, 0, 0, 0, 0, 0, SF_Values
,0);
1100 pSel
->pPrior
= pRet
;
1106 if( pRet
&& pRet
->pPrior
){
1107 pRet
->selFlags
|= SF_MultiValue
;
1109 sqlite3ExprListDelete(pParse
->db
, pEList
);
1114 ** Join two expressions using an AND operator. If either expression is
1115 ** NULL, then just return the other expression.
1117 ** If one side or the other of the AND is known to be false, then instead
1118 ** of returning an AND expression, just return a constant expression with
1119 ** a value of false.
1121 Expr
*sqlite3ExprAnd(Parse
*pParse
, Expr
*pLeft
, Expr
*pRight
){
1122 sqlite3
*db
= pParse
->db
;
1125 }else if( pRight
==0 ){
1127 }else if( (ExprAlwaysFalse(pLeft
) || ExprAlwaysFalse(pRight
))
1128 && !IN_RENAME_OBJECT
1130 sqlite3ExprDeferredDelete(pParse
, pLeft
);
1131 sqlite3ExprDeferredDelete(pParse
, pRight
);
1132 return sqlite3Expr(db
, TK_INTEGER
, "0");
1134 return sqlite3PExpr(pParse
, TK_AND
, pLeft
, pRight
);
1139 ** Construct a new expression node for a function with multiple
1142 Expr
*sqlite3ExprFunction(
1143 Parse
*pParse
, /* Parsing context */
1144 ExprList
*pList
, /* Argument list */
1145 const Token
*pToken
, /* Name of the function */
1146 int eDistinct
/* SF_Distinct or SF_ALL or 0 */
1149 sqlite3
*db
= pParse
->db
;
1151 pNew
= sqlite3ExprAlloc(db
, TK_FUNCTION
, pToken
, 1);
1153 sqlite3ExprListDelete(db
, pList
); /* Avoid memory leak when malloc fails */
1156 assert( !ExprHasProperty(pNew
, EP_InnerON
|EP_OuterON
) );
1157 pNew
->w
.iOfst
= (int)(pToken
->z
- pParse
->zTail
);
1159 && pList
->nExpr
> pParse
->db
->aLimit
[SQLITE_LIMIT_FUNCTION_ARG
]
1162 sqlite3ErrorMsg(pParse
, "too many arguments on function %T", pToken
);
1164 pNew
->x
.pList
= pList
;
1165 ExprSetProperty(pNew
, EP_HasFunc
);
1166 assert( ExprUseXList(pNew
) );
1167 sqlite3ExprSetHeightAndFlags(pParse
, pNew
);
1168 if( eDistinct
==SF_Distinct
) ExprSetProperty(pNew
, EP_Distinct
);
1173 ** Check to see if a function is usable according to current access
1176 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1178 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1181 ** If the function is not usable, create an error.
1183 void sqlite3ExprFunctionUsable(
1184 Parse
*pParse
, /* Parsing and code generating context */
1185 const Expr
*pExpr
, /* The function invocation */
1186 const FuncDef
*pDef
/* The function being invoked */
1188 assert( !IN_RENAME_OBJECT
);
1189 assert( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0 );
1190 if( ExprHasProperty(pExpr
, EP_FromDDL
) ){
1191 if( (pDef
->funcFlags
& SQLITE_FUNC_DIRECT
)!=0
1192 || (pParse
->db
->flags
& SQLITE_TrustedSchema
)==0
1194 /* Functions prohibited in triggers and views if:
1195 ** (1) tagged with SQLITE_DIRECTONLY
1196 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1197 ** is tagged with SQLITE_FUNC_UNSAFE) and
1198 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1199 ** that the schema is possibly tainted).
1201 sqlite3ErrorMsg(pParse
, "unsafe use of %#T()", pExpr
);
1207 ** Assign a variable number to an expression that encodes a wildcard
1208 ** in the original SQL statement.
1210 ** Wildcards consisting of a single "?" are assigned the next sequential
1213 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1214 ** sure "nnn" is not too big to avoid a denial of service attack when
1215 ** the SQL statement comes from an external source.
1217 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1218 ** as the previous instance of the same wildcard. Or if this is the first
1219 ** instance of the wildcard, the next sequential variable number is
1222 void sqlite3ExprAssignVarNumber(Parse
*pParse
, Expr
*pExpr
, u32 n
){
1223 sqlite3
*db
= pParse
->db
;
1227 if( pExpr
==0 ) return;
1228 assert( !ExprHasProperty(pExpr
, EP_IntValue
|EP_Reduced
|EP_TokenOnly
) );
1229 z
= pExpr
->u
.zToken
;
1232 assert( n
==(u32
)sqlite3Strlen30(z
) );
1234 /* Wildcard of the form "?". Assign the next variable number */
1235 assert( z
[0]=='?' );
1236 x
= (ynVar
)(++pParse
->nVar
);
1240 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1241 ** use it as the variable number */
1244 if( n
==2 ){ /*OPTIMIZATION-IF-TRUE*/
1245 i
= z
[1]-'0'; /* The common case of ?N for a single digit N */
1248 bOk
= 0==sqlite3Atoi64(&z
[1], &i
, n
-1, SQLITE_UTF8
);
1252 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]-1 );
1253 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] );
1254 if( bOk
==0 || i
<1 || i
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
1255 sqlite3ErrorMsg(pParse
, "variable number must be between ?1 and ?%d",
1256 db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]);
1257 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1261 if( x
>pParse
->nVar
){
1262 pParse
->nVar
= (int)x
;
1264 }else if( sqlite3VListNumToName(pParse
->pVList
, x
)==0 ){
1268 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1269 ** number as the prior appearance of the same name, or if the name
1270 ** has never appeared before, reuse the same variable number
1272 x
= (ynVar
)sqlite3VListNameToNum(pParse
->pVList
, z
, n
);
1274 x
= (ynVar
)(++pParse
->nVar
);
1279 pParse
->pVList
= sqlite3VListAdd(db
, pParse
->pVList
, z
, n
, x
);
1283 if( x
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
1284 sqlite3ErrorMsg(pParse
, "too many SQL variables");
1285 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1290 ** Recursively delete an expression tree.
1292 static SQLITE_NOINLINE
void sqlite3ExprDeleteNN(sqlite3
*db
, Expr
*p
){
1295 assert( !ExprUseUValue(p
) || p
->u
.iValue
>=0 );
1296 assert( !ExprUseYWin(p
) || !ExprUseYSub(p
) );
1297 assert( !ExprUseYWin(p
) || p
->y
.pWin
!=0 || db
->mallocFailed
);
1298 assert( p
->op
!=TK_FUNCTION
|| !ExprUseYSub(p
) );
1300 if( ExprHasProperty(p
, EP_Leaf
) && !ExprHasProperty(p
, EP_TokenOnly
) ){
1301 assert( p
->pLeft
==0 );
1302 assert( p
->pRight
==0 );
1303 assert( !ExprUseXSelect(p
) || p
->x
.pSelect
==0 );
1304 assert( !ExprUseXList(p
) || p
->x
.pList
==0 );
1307 if( !ExprHasProperty(p
, (EP_TokenOnly
|EP_Leaf
)) ){
1308 /* The Expr.x union is never used at the same time as Expr.pRight */
1309 assert( (ExprUseXList(p
) && p
->x
.pList
==0) || p
->pRight
==0 );
1310 if( p
->pLeft
&& p
->op
!=TK_SELECT_COLUMN
) sqlite3ExprDeleteNN(db
, p
->pLeft
);
1312 assert( !ExprHasProperty(p
, EP_WinFunc
) );
1313 sqlite3ExprDeleteNN(db
, p
->pRight
);
1314 }else if( ExprUseXSelect(p
) ){
1315 assert( !ExprHasProperty(p
, EP_WinFunc
) );
1316 sqlite3SelectDelete(db
, p
->x
.pSelect
);
1318 sqlite3ExprListDelete(db
, p
->x
.pList
);
1319 #ifndef SQLITE_OMIT_WINDOWFUNC
1320 if( ExprHasProperty(p
, EP_WinFunc
) ){
1321 sqlite3WindowDelete(db
, p
->y
.pWin
);
1326 if( !ExprHasProperty(p
, EP_Static
) ){
1327 sqlite3DbNNFreeNN(db
, p
);
1330 void sqlite3ExprDelete(sqlite3
*db
, Expr
*p
){
1331 if( p
) sqlite3ExprDeleteNN(db
, p
);
1335 ** Clear both elements of an OnOrUsing object
1337 void sqlite3ClearOnOrUsing(sqlite3
*db
, OnOrUsing
*p
){
1339 /* Nothing to clear */
1341 sqlite3ExprDeleteNN(db
, p
->pOn
);
1342 }else if( p
->pUsing
){
1343 sqlite3IdListDelete(db
, p
->pUsing
);
1348 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1349 ** This is similar to sqlite3ExprDelete() except that the delete is
1350 ** deferred untilthe pParse is deleted.
1352 ** The pExpr might be deleted immediately on an OOM error.
1354 ** The deferred delete is (currently) implemented by adding the
1355 ** pExpr to the pParse->pConstExpr list with a register number of 0.
1357 void sqlite3ExprDeferredDelete(Parse
*pParse
, Expr
*pExpr
){
1358 sqlite3ParserAddCleanup(pParse
,
1359 (void(*)(sqlite3
*,void*))sqlite3ExprDelete
,
1363 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1366 void sqlite3ExprUnmapAndDelete(Parse
*pParse
, Expr
*p
){
1368 if( IN_RENAME_OBJECT
){
1369 sqlite3RenameExprUnmap(pParse
, p
);
1371 sqlite3ExprDeleteNN(pParse
->db
, p
);
1376 ** Return the number of bytes allocated for the expression structure
1377 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1378 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1380 static int exprStructSize(const Expr
*p
){
1381 if( ExprHasProperty(p
, EP_TokenOnly
) ) return EXPR_TOKENONLYSIZE
;
1382 if( ExprHasProperty(p
, EP_Reduced
) ) return EXPR_REDUCEDSIZE
;
1383 return EXPR_FULLSIZE
;
1387 ** The dupedExpr*Size() routines each return the number of bytes required
1388 ** to store a copy of an expression or expression tree. They differ in
1389 ** how much of the tree is measured.
1391 ** dupedExprStructSize() Size of only the Expr structure
1392 ** dupedExprNodeSize() Size of Expr + space for token
1393 ** dupedExprSize() Expr + token + subtree components
1395 ***************************************************************************
1397 ** The dupedExprStructSize() function returns two values OR-ed together:
1398 ** (1) the space required for a copy of the Expr structure only and
1399 ** (2) the EP_xxx flags that indicate what the structure size should be.
1400 ** The return values is always one of:
1403 ** EXPR_REDUCEDSIZE | EP_Reduced
1404 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1406 ** The size of the structure can be found by masking the return value
1407 ** of this routine with 0xfff. The flags can be found by masking the
1408 ** return value with EP_Reduced|EP_TokenOnly.
1410 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1411 ** (unreduced) Expr objects as they or originally constructed by the parser.
1412 ** During expression analysis, extra information is computed and moved into
1413 ** later parts of the Expr object and that extra information might get chopped
1414 ** off if the expression is reduced. Note also that it does not work to
1415 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1416 ** to reduce a pristine expression tree from the parser. The implementation
1417 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1418 ** to enforce this constraint.
1420 static int dupedExprStructSize(const Expr
*p
, int flags
){
1422 assert( flags
==EXPRDUP_REDUCE
|| flags
==0 ); /* Only one flag value allowed */
1423 assert( EXPR_FULLSIZE
<=0xfff );
1424 assert( (0xfff & (EP_Reduced
|EP_TokenOnly
))==0 );
1425 if( 0==flags
|| p
->op
==TK_SELECT_COLUMN
1426 #ifndef SQLITE_OMIT_WINDOWFUNC
1427 || ExprHasProperty(p
, EP_WinFunc
)
1430 nSize
= EXPR_FULLSIZE
;
1432 assert( !ExprHasProperty(p
, EP_TokenOnly
|EP_Reduced
) );
1433 assert( !ExprHasProperty(p
, EP_OuterON
) );
1434 assert( !ExprHasVVAProperty(p
, EP_NoReduce
) );
1435 if( p
->pLeft
|| p
->x
.pList
){
1436 nSize
= EXPR_REDUCEDSIZE
| EP_Reduced
;
1438 assert( p
->pRight
==0 );
1439 nSize
= EXPR_TOKENONLYSIZE
| EP_TokenOnly
;
1446 ** This function returns the space in bytes required to store the copy
1447 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1448 ** string is defined.)
1450 static int dupedExprNodeSize(const Expr
*p
, int flags
){
1451 int nByte
= dupedExprStructSize(p
, flags
) & 0xfff;
1452 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1453 nByte
+= sqlite3Strlen30NN(p
->u
.zToken
)+1;
1455 return ROUND8(nByte
);
1459 ** Return the number of bytes required to create a duplicate of the
1460 ** expression passed as the first argument. The second argument is a
1461 ** mask containing EXPRDUP_XXX flags.
1463 ** The value returned includes space to create a copy of the Expr struct
1464 ** itself and the buffer referred to by Expr.u.zToken, if any.
1466 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
1467 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1468 ** and Expr.pRight variables (but not for any structures pointed to or
1469 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
1471 static int dupedExprSize(const Expr
*p
, int flags
){
1474 nByte
= dupedExprNodeSize(p
, flags
);
1475 if( flags
&EXPRDUP_REDUCE
){
1476 nByte
+= dupedExprSize(p
->pLeft
, flags
) + dupedExprSize(p
->pRight
, flags
);
1483 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1484 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
1485 ** to store the copy of expression p, the copies of p->u.zToken
1486 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
1487 ** if any. Before returning, *pzBuffer is set to the first byte past the
1488 ** portion of the buffer copied into by this function.
1490 static Expr
*exprDup(sqlite3
*db
, const Expr
*p
, int dupFlags
, u8
**pzBuffer
){
1491 Expr
*pNew
; /* Value to return */
1492 u8
*zAlloc
; /* Memory space from which to build Expr object */
1493 u32 staticFlag
; /* EP_Static if space not obtained from malloc */
1497 assert( dupFlags
==0 || dupFlags
==EXPRDUP_REDUCE
);
1498 assert( pzBuffer
==0 || dupFlags
==EXPRDUP_REDUCE
);
1500 /* Figure out where to write the new Expr structure. */
1503 staticFlag
= EP_Static
;
1504 assert( zAlloc
!=0 );
1506 zAlloc
= sqlite3DbMallocRawNN(db
, dupedExprSize(p
, dupFlags
));
1509 pNew
= (Expr
*)zAlloc
;
1512 /* Set nNewSize to the size allocated for the structure pointed to
1513 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1514 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1515 ** by the copy of the p->u.zToken string (if any).
1517 const unsigned nStructSize
= dupedExprStructSize(p
, dupFlags
);
1518 const int nNewSize
= nStructSize
& 0xfff;
1520 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1521 nToken
= sqlite3Strlen30(p
->u
.zToken
) + 1;
1526 assert( ExprHasProperty(p
, EP_Reduced
)==0 );
1527 memcpy(zAlloc
, p
, nNewSize
);
1529 u32 nSize
= (u32
)exprStructSize(p
);
1530 memcpy(zAlloc
, p
, nSize
);
1531 if( nSize
<EXPR_FULLSIZE
){
1532 memset(&zAlloc
[nSize
], 0, EXPR_FULLSIZE
-nSize
);
1536 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1537 pNew
->flags
&= ~(EP_Reduced
|EP_TokenOnly
|EP_Static
);
1538 pNew
->flags
|= nStructSize
& (EP_Reduced
|EP_TokenOnly
);
1539 pNew
->flags
|= staticFlag
;
1540 ExprClearVVAProperties(pNew
);
1542 ExprSetVVAProperty(pNew
, EP_Immutable
);
1545 /* Copy the p->u.zToken string, if any. */
1547 char *zToken
= pNew
->u
.zToken
= (char*)&zAlloc
[nNewSize
];
1548 memcpy(zToken
, p
->u
.zToken
, nToken
);
1551 if( 0==((p
->flags
|pNew
->flags
) & (EP_TokenOnly
|EP_Leaf
)) ){
1552 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1553 if( ExprUseXSelect(p
) ){
1554 pNew
->x
.pSelect
= sqlite3SelectDup(db
, p
->x
.pSelect
, dupFlags
);
1556 pNew
->x
.pList
= sqlite3ExprListDup(db
, p
->x
.pList
, dupFlags
);
1560 /* Fill in pNew->pLeft and pNew->pRight. */
1561 if( ExprHasProperty(pNew
, EP_Reduced
|EP_TokenOnly
|EP_WinFunc
) ){
1562 zAlloc
+= dupedExprNodeSize(p
, dupFlags
);
1563 if( !ExprHasProperty(pNew
, EP_TokenOnly
|EP_Leaf
) ){
1564 pNew
->pLeft
= p
->pLeft
?
1565 exprDup(db
, p
->pLeft
, EXPRDUP_REDUCE
, &zAlloc
) : 0;
1566 pNew
->pRight
= p
->pRight
?
1567 exprDup(db
, p
->pRight
, EXPRDUP_REDUCE
, &zAlloc
) : 0;
1569 #ifndef SQLITE_OMIT_WINDOWFUNC
1570 if( ExprHasProperty(p
, EP_WinFunc
) ){
1571 pNew
->y
.pWin
= sqlite3WindowDup(db
, pNew
, p
->y
.pWin
);
1572 assert( ExprHasProperty(pNew
, EP_WinFunc
) );
1574 #endif /* SQLITE_OMIT_WINDOWFUNC */
1579 if( !ExprHasProperty(p
, EP_TokenOnly
|EP_Leaf
) ){
1580 if( pNew
->op
==TK_SELECT_COLUMN
){
1581 pNew
->pLeft
= p
->pLeft
;
1582 assert( p
->pRight
==0 || p
->pRight
==p
->pLeft
1583 || ExprHasProperty(p
->pLeft
, EP_Subquery
) );
1585 pNew
->pLeft
= sqlite3ExprDup(db
, p
->pLeft
, 0);
1587 pNew
->pRight
= sqlite3ExprDup(db
, p
->pRight
, 0);
1595 ** Create and return a deep copy of the object passed as the second
1596 ** argument. If an OOM condition is encountered, NULL is returned
1597 ** and the db->mallocFailed flag set.
1599 #ifndef SQLITE_OMIT_CTE
1600 With
*sqlite3WithDup(sqlite3
*db
, With
*p
){
1603 sqlite3_int64 nByte
= sizeof(*p
) + sizeof(p
->a
[0]) * (p
->nCte
-1);
1604 pRet
= sqlite3DbMallocZero(db
, nByte
);
1607 pRet
->nCte
= p
->nCte
;
1608 for(i
=0; i
<p
->nCte
; i
++){
1609 pRet
->a
[i
].pSelect
= sqlite3SelectDup(db
, p
->a
[i
].pSelect
, 0);
1610 pRet
->a
[i
].pCols
= sqlite3ExprListDup(db
, p
->a
[i
].pCols
, 0);
1611 pRet
->a
[i
].zName
= sqlite3DbStrDup(db
, p
->a
[i
].zName
);
1612 pRet
->a
[i
].eM10d
= p
->a
[i
].eM10d
;
1619 # define sqlite3WithDup(x,y) 0
1622 #ifndef SQLITE_OMIT_WINDOWFUNC
1624 ** The gatherSelectWindows() procedure and its helper routine
1625 ** gatherSelectWindowsCallback() are used to scan all the expressions
1626 ** an a newly duplicated SELECT statement and gather all of the Window
1627 ** objects found there, assembling them onto the linked list at Select->pWin.
1629 static int gatherSelectWindowsCallback(Walker
*pWalker
, Expr
*pExpr
){
1630 if( pExpr
->op
==TK_FUNCTION
&& ExprHasProperty(pExpr
, EP_WinFunc
) ){
1631 Select
*pSelect
= pWalker
->u
.pSelect
;
1632 Window
*pWin
= pExpr
->y
.pWin
;
1634 assert( IsWindowFunc(pExpr
) );
1635 assert( pWin
->ppThis
==0 );
1636 sqlite3WindowLink(pSelect
, pWin
);
1638 return WRC_Continue
;
1640 static int gatherSelectWindowsSelectCallback(Walker
*pWalker
, Select
*p
){
1641 return p
==pWalker
->u
.pSelect
? WRC_Continue
: WRC_Prune
;
1643 static void gatherSelectWindows(Select
*p
){
1645 w
.xExprCallback
= gatherSelectWindowsCallback
;
1646 w
.xSelectCallback
= gatherSelectWindowsSelectCallback
;
1647 w
.xSelectCallback2
= 0;
1650 sqlite3WalkSelect(&w
, p
);
1656 ** The following group of routines make deep copies of expressions,
1657 ** expression lists, ID lists, and select statements. The copies can
1658 ** be deleted (by being passed to their respective ...Delete() routines)
1659 ** without effecting the originals.
1661 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1662 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1663 ** by subsequent calls to sqlite*ListAppend() routines.
1665 ** Any tables that the SrcList might point to are not duplicated.
1667 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1668 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1669 ** truncated version of the usual Expr structure that will be stored as
1670 ** part of the in-memory representation of the database schema.
1672 Expr
*sqlite3ExprDup(sqlite3
*db
, const Expr
*p
, int flags
){
1673 assert( flags
==0 || flags
==EXPRDUP_REDUCE
);
1674 return p
? exprDup(db
, p
, flags
, 0) : 0;
1676 ExprList
*sqlite3ExprListDup(sqlite3
*db
, const ExprList
*p
, int flags
){
1678 struct ExprList_item
*pItem
;
1679 const struct ExprList_item
*pOldItem
;
1681 Expr
*pPriorSelectColOld
= 0;
1682 Expr
*pPriorSelectColNew
= 0;
1684 if( p
==0 ) return 0;
1685 pNew
= sqlite3DbMallocRawNN(db
, sqlite3DbMallocSize(db
, p
));
1686 if( pNew
==0 ) return 0;
1687 pNew
->nExpr
= p
->nExpr
;
1688 pNew
->nAlloc
= p
->nAlloc
;
1691 for(i
=0; i
<p
->nExpr
; i
++, pItem
++, pOldItem
++){
1692 Expr
*pOldExpr
= pOldItem
->pExpr
;
1694 pItem
->pExpr
= sqlite3ExprDup(db
, pOldExpr
, flags
);
1696 && pOldExpr
->op
==TK_SELECT_COLUMN
1697 && (pNewExpr
= pItem
->pExpr
)!=0
1699 if( pNewExpr
->pRight
){
1700 pPriorSelectColOld
= pOldExpr
->pRight
;
1701 pPriorSelectColNew
= pNewExpr
->pRight
;
1702 pNewExpr
->pLeft
= pNewExpr
->pRight
;
1704 if( pOldExpr
->pLeft
!=pPriorSelectColOld
){
1705 pPriorSelectColOld
= pOldExpr
->pLeft
;
1706 pPriorSelectColNew
= sqlite3ExprDup(db
, pPriorSelectColOld
, flags
);
1707 pNewExpr
->pRight
= pPriorSelectColNew
;
1709 pNewExpr
->pLeft
= pPriorSelectColNew
;
1712 pItem
->zEName
= sqlite3DbStrDup(db
, pOldItem
->zEName
);
1713 pItem
->fg
= pOldItem
->fg
;
1715 pItem
->u
= pOldItem
->u
;
1721 ** If cursors, triggers, views and subqueries are all omitted from
1722 ** the build, then none of the following routines, except for
1723 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1724 ** called with a NULL argument.
1726 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1727 || !defined(SQLITE_OMIT_SUBQUERY)
1728 SrcList
*sqlite3SrcListDup(sqlite3
*db
, const SrcList
*p
, int flags
){
1733 if( p
==0 ) return 0;
1734 nByte
= sizeof(*p
) + (p
->nSrc
>0 ? sizeof(p
->a
[0]) * (p
->nSrc
-1) : 0);
1735 pNew
= sqlite3DbMallocRawNN(db
, nByte
);
1736 if( pNew
==0 ) return 0;
1737 pNew
->nSrc
= pNew
->nAlloc
= p
->nSrc
;
1738 for(i
=0; i
<p
->nSrc
; i
++){
1739 SrcItem
*pNewItem
= &pNew
->a
[i
];
1740 const SrcItem
*pOldItem
= &p
->a
[i
];
1742 pNewItem
->pSchema
= pOldItem
->pSchema
;
1743 pNewItem
->zDatabase
= sqlite3DbStrDup(db
, pOldItem
->zDatabase
);
1744 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1745 pNewItem
->zAlias
= sqlite3DbStrDup(db
, pOldItem
->zAlias
);
1746 pNewItem
->fg
= pOldItem
->fg
;
1747 pNewItem
->iCursor
= pOldItem
->iCursor
;
1748 pNewItem
->addrFillSub
= pOldItem
->addrFillSub
;
1749 pNewItem
->regReturn
= pOldItem
->regReturn
;
1750 if( pNewItem
->fg
.isIndexedBy
){
1751 pNewItem
->u1
.zIndexedBy
= sqlite3DbStrDup(db
, pOldItem
->u1
.zIndexedBy
);
1753 pNewItem
->u2
= pOldItem
->u2
;
1754 if( pNewItem
->fg
.isCte
){
1755 pNewItem
->u2
.pCteUse
->nUse
++;
1757 if( pNewItem
->fg
.isTabFunc
){
1758 pNewItem
->u1
.pFuncArg
=
1759 sqlite3ExprListDup(db
, pOldItem
->u1
.pFuncArg
, flags
);
1761 pTab
= pNewItem
->pTab
= pOldItem
->pTab
;
1765 pNewItem
->pSelect
= sqlite3SelectDup(db
, pOldItem
->pSelect
, flags
);
1766 if( pOldItem
->fg
.isUsing
){
1767 assert( pNewItem
->fg
.isUsing
);
1768 pNewItem
->u3
.pUsing
= sqlite3IdListDup(db
, pOldItem
->u3
.pUsing
);
1770 pNewItem
->u3
.pOn
= sqlite3ExprDup(db
, pOldItem
->u3
.pOn
, flags
);
1772 pNewItem
->colUsed
= pOldItem
->colUsed
;
1776 IdList
*sqlite3IdListDup(sqlite3
*db
, const IdList
*p
){
1780 if( p
==0 ) return 0;
1781 assert( p
->eU4
!=EU4_EXPR
);
1782 pNew
= sqlite3DbMallocRawNN(db
, sizeof(*pNew
)+(p
->nId
-1)*sizeof(p
->a
[0]) );
1783 if( pNew
==0 ) return 0;
1786 for(i
=0; i
<p
->nId
; i
++){
1787 struct IdList_item
*pNewItem
= &pNew
->a
[i
];
1788 const struct IdList_item
*pOldItem
= &p
->a
[i
];
1789 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1790 pNewItem
->u4
= pOldItem
->u4
;
1794 Select
*sqlite3SelectDup(sqlite3
*db
, const Select
*pDup
, int flags
){
1797 Select
**pp
= &pRet
;
1801 for(p
=pDup
; p
; p
=p
->pPrior
){
1802 Select
*pNew
= sqlite3DbMallocRawNN(db
, sizeof(*p
) );
1803 if( pNew
==0 ) break;
1804 pNew
->pEList
= sqlite3ExprListDup(db
, p
->pEList
, flags
);
1805 pNew
->pSrc
= sqlite3SrcListDup(db
, p
->pSrc
, flags
);
1806 pNew
->pWhere
= sqlite3ExprDup(db
, p
->pWhere
, flags
);
1807 pNew
->pGroupBy
= sqlite3ExprListDup(db
, p
->pGroupBy
, flags
);
1808 pNew
->pHaving
= sqlite3ExprDup(db
, p
->pHaving
, flags
);
1809 pNew
->pOrderBy
= sqlite3ExprListDup(db
, p
->pOrderBy
, flags
);
1811 pNew
->pNext
= pNext
;
1813 pNew
->pLimit
= sqlite3ExprDup(db
, p
->pLimit
, flags
);
1816 pNew
->selFlags
= p
->selFlags
& ~SF_UsesEphemeral
;
1817 pNew
->addrOpenEphm
[0] = -1;
1818 pNew
->addrOpenEphm
[1] = -1;
1819 pNew
->nSelectRow
= p
->nSelectRow
;
1820 pNew
->pWith
= sqlite3WithDup(db
, p
->pWith
);
1821 #ifndef SQLITE_OMIT_WINDOWFUNC
1823 pNew
->pWinDefn
= sqlite3WindowListDup(db
, p
->pWinDefn
);
1824 if( p
->pWin
&& db
->mallocFailed
==0 ) gatherSelectWindows(pNew
);
1826 pNew
->selId
= p
->selId
;
1827 if( db
->mallocFailed
){
1828 /* Any prior OOM might have left the Select object incomplete.
1829 ** Delete the whole thing rather than allow an incomplete Select
1830 ** to be used by the code generator. */
1832 sqlite3SelectDelete(db
, pNew
);
1843 Select
*sqlite3SelectDup(sqlite3
*db
, const Select
*p
, int flags
){
1851 ** Add a new element to the end of an expression list. If pList is
1852 ** initially NULL, then create a new expression list.
1854 ** The pList argument must be either NULL or a pointer to an ExprList
1855 ** obtained from a prior call to sqlite3ExprListAppend(). This routine
1856 ** may not be used with an ExprList obtained from sqlite3ExprListDup().
1857 ** Reason: This routine assumes that the number of slots in pList->a[]
1858 ** is a power of two. That is true for sqlite3ExprListAppend() returns
1859 ** but is not necessarily true from the return value of sqlite3ExprListDup().
1861 ** If a memory allocation error occurs, the entire list is freed and
1862 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1863 ** that the new entry was successfully appended.
1865 static const struct ExprList_item zeroItem
= {0};
1866 SQLITE_NOINLINE ExprList
*sqlite3ExprListAppendNew(
1867 sqlite3
*db
, /* Database handle. Used for memory allocation */
1868 Expr
*pExpr
/* Expression to be appended. Might be NULL */
1870 struct ExprList_item
*pItem
;
1873 pList
= sqlite3DbMallocRawNN(db
, sizeof(ExprList
)+sizeof(pList
->a
[0])*4 );
1875 sqlite3ExprDelete(db
, pExpr
);
1880 pItem
= &pList
->a
[0];
1882 pItem
->pExpr
= pExpr
;
1885 SQLITE_NOINLINE ExprList
*sqlite3ExprListAppendGrow(
1886 sqlite3
*db
, /* Database handle. Used for memory allocation */
1887 ExprList
*pList
, /* List to which to append. Might be NULL */
1888 Expr
*pExpr
/* Expression to be appended. Might be NULL */
1890 struct ExprList_item
*pItem
;
1893 pNew
= sqlite3DbRealloc(db
, pList
,
1894 sizeof(*pList
)+(pList
->nAlloc
-1)*sizeof(pList
->a
[0]));
1896 sqlite3ExprListDelete(db
, pList
);
1897 sqlite3ExprDelete(db
, pExpr
);
1902 pItem
= &pList
->a
[pList
->nExpr
++];
1904 pItem
->pExpr
= pExpr
;
1907 ExprList
*sqlite3ExprListAppend(
1908 Parse
*pParse
, /* Parsing context */
1909 ExprList
*pList
, /* List to which to append. Might be NULL */
1910 Expr
*pExpr
/* Expression to be appended. Might be NULL */
1912 struct ExprList_item
*pItem
;
1914 return sqlite3ExprListAppendNew(pParse
->db
,pExpr
);
1916 if( pList
->nAlloc
<pList
->nExpr
+1 ){
1917 return sqlite3ExprListAppendGrow(pParse
->db
,pList
,pExpr
);
1919 pItem
= &pList
->a
[pList
->nExpr
++];
1921 pItem
->pExpr
= pExpr
;
1926 ** pColumns and pExpr form a vector assignment which is part of the SET
1927 ** clause of an UPDATE statement. Like this:
1929 ** (a,b,c) = (expr1,expr2,expr3)
1930 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1932 ** For each term of the vector assignment, append new entries to the
1933 ** expression list pList. In the case of a subquery on the RHS, append
1934 ** TK_SELECT_COLUMN expressions.
1936 ExprList
*sqlite3ExprListAppendVector(
1937 Parse
*pParse
, /* Parsing context */
1938 ExprList
*pList
, /* List to which to append. Might be NULL */
1939 IdList
*pColumns
, /* List of names of LHS of the assignment */
1940 Expr
*pExpr
/* Vector expression to be appended. Might be NULL */
1942 sqlite3
*db
= pParse
->db
;
1945 int iFirst
= pList
? pList
->nExpr
: 0;
1946 /* pColumns can only be NULL due to an OOM but an OOM will cause an
1947 ** exit prior to this routine being invoked */
1948 if( NEVER(pColumns
==0) ) goto vector_append_error
;
1949 if( pExpr
==0 ) goto vector_append_error
;
1951 /* If the RHS is a vector, then we can immediately check to see that
1952 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
1953 ** wildcards ("*") in the result set of the SELECT must be expanded before
1954 ** we can do the size check, so defer the size check until code generation.
1956 if( pExpr
->op
!=TK_SELECT
&& pColumns
->nId
!=(n
=sqlite3ExprVectorSize(pExpr
)) ){
1957 sqlite3ErrorMsg(pParse
, "%d columns assigned %d values",
1959 goto vector_append_error
;
1962 for(i
=0; i
<pColumns
->nId
; i
++){
1963 Expr
*pSubExpr
= sqlite3ExprForVectorField(pParse
, pExpr
, i
, pColumns
->nId
);
1964 assert( pSubExpr
!=0 || db
->mallocFailed
);
1965 if( pSubExpr
==0 ) continue;
1966 pList
= sqlite3ExprListAppend(pParse
, pList
, pSubExpr
);
1968 assert( pList
->nExpr
==iFirst
+i
+1 );
1969 pList
->a
[pList
->nExpr
-1].zEName
= pColumns
->a
[i
].zName
;
1970 pColumns
->a
[i
].zName
= 0;
1974 if( !db
->mallocFailed
&& pExpr
->op
==TK_SELECT
&& ALWAYS(pList
!=0) ){
1975 Expr
*pFirst
= pList
->a
[iFirst
].pExpr
;
1976 assert( pFirst
!=0 );
1977 assert( pFirst
->op
==TK_SELECT_COLUMN
);
1979 /* Store the SELECT statement in pRight so it will be deleted when
1980 ** sqlite3ExprListDelete() is called */
1981 pFirst
->pRight
= pExpr
;
1984 /* Remember the size of the LHS in iTable so that we can check that
1985 ** the RHS and LHS sizes match during code generation. */
1986 pFirst
->iTable
= pColumns
->nId
;
1989 vector_append_error
:
1990 sqlite3ExprUnmapAndDelete(pParse
, pExpr
);
1991 sqlite3IdListDelete(db
, pColumns
);
1996 ** Set the sort order for the last element on the given ExprList.
1998 void sqlite3ExprListSetSortOrder(ExprList
*p
, int iSortOrder
, int eNulls
){
1999 struct ExprList_item
*pItem
;
2001 assert( p
->nExpr
>0 );
2003 assert( SQLITE_SO_UNDEFINED
<0 && SQLITE_SO_ASC
==0 && SQLITE_SO_DESC
>0 );
2004 assert( iSortOrder
==SQLITE_SO_UNDEFINED
2005 || iSortOrder
==SQLITE_SO_ASC
2006 || iSortOrder
==SQLITE_SO_DESC
2008 assert( eNulls
==SQLITE_SO_UNDEFINED
2009 || eNulls
==SQLITE_SO_ASC
2010 || eNulls
==SQLITE_SO_DESC
2013 pItem
= &p
->a
[p
->nExpr
-1];
2014 assert( pItem
->fg
.bNulls
==0 );
2015 if( iSortOrder
==SQLITE_SO_UNDEFINED
){
2016 iSortOrder
= SQLITE_SO_ASC
;
2018 pItem
->fg
.sortFlags
= (u8
)iSortOrder
;
2020 if( eNulls
!=SQLITE_SO_UNDEFINED
){
2021 pItem
->fg
.bNulls
= 1;
2022 if( iSortOrder
!=eNulls
){
2023 pItem
->fg
.sortFlags
|= KEYINFO_ORDER_BIGNULL
;
2029 ** Set the ExprList.a[].zEName element of the most recently added item
2030 ** on the expression list.
2032 ** pList might be NULL following an OOM error. But pName should never be
2033 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2036 void sqlite3ExprListSetName(
2037 Parse
*pParse
, /* Parsing context */
2038 ExprList
*pList
, /* List to which to add the span. */
2039 const Token
*pName
, /* Name to be added */
2040 int dequote
/* True to cause the name to be dequoted */
2042 assert( pList
!=0 || pParse
->db
->mallocFailed
!=0 );
2043 assert( pParse
->eParseMode
!=PARSE_MODE_UNMAP
|| dequote
==0 );
2045 struct ExprList_item
*pItem
;
2046 assert( pList
->nExpr
>0 );
2047 pItem
= &pList
->a
[pList
->nExpr
-1];
2048 assert( pItem
->zEName
==0 );
2049 assert( pItem
->fg
.eEName
==ENAME_NAME
);
2050 pItem
->zEName
= sqlite3DbStrNDup(pParse
->db
, pName
->z
, pName
->n
);
2052 /* If dequote==0, then pName->z does not point to part of a DDL
2053 ** statement handled by the parser. And so no token need be added
2054 ** to the token-map. */
2055 sqlite3Dequote(pItem
->zEName
);
2056 if( IN_RENAME_OBJECT
){
2057 sqlite3RenameTokenMap(pParse
, (const void*)pItem
->zEName
, pName
);
2064 ** Set the ExprList.a[].zSpan element of the most recently added item
2065 ** on the expression list.
2067 ** pList might be NULL following an OOM error. But pSpan should never be
2068 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2071 void sqlite3ExprListSetSpan(
2072 Parse
*pParse
, /* Parsing context */
2073 ExprList
*pList
, /* List to which to add the span. */
2074 const char *zStart
, /* Start of the span */
2075 const char *zEnd
/* End of the span */
2077 sqlite3
*db
= pParse
->db
;
2078 assert( pList
!=0 || db
->mallocFailed
!=0 );
2080 struct ExprList_item
*pItem
= &pList
->a
[pList
->nExpr
-1];
2081 assert( pList
->nExpr
>0 );
2082 if( pItem
->zEName
==0 ){
2083 pItem
->zEName
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
2084 pItem
->fg
.eEName
= ENAME_SPAN
;
2090 ** If the expression list pEList contains more than iLimit elements,
2091 ** leave an error message in pParse.
2093 void sqlite3ExprListCheckLength(
2098 int mx
= pParse
->db
->aLimit
[SQLITE_LIMIT_COLUMN
];
2099 testcase( pEList
&& pEList
->nExpr
==mx
);
2100 testcase( pEList
&& pEList
->nExpr
==mx
+1 );
2101 if( pEList
&& pEList
->nExpr
>mx
){
2102 sqlite3ErrorMsg(pParse
, "too many columns in %s", zObject
);
2107 ** Delete an entire expression list.
2109 static SQLITE_NOINLINE
void exprListDeleteNN(sqlite3
*db
, ExprList
*pList
){
2110 int i
= pList
->nExpr
;
2111 struct ExprList_item
*pItem
= pList
->a
;
2112 assert( pList
->nExpr
>0 );
2115 sqlite3ExprDelete(db
, pItem
->pExpr
);
2116 if( pItem
->zEName
) sqlite3DbNNFreeNN(db
, pItem
->zEName
);
2119 sqlite3DbNNFreeNN(db
, pList
);
2121 void sqlite3ExprListDelete(sqlite3
*db
, ExprList
*pList
){
2122 if( pList
) exprListDeleteNN(db
, pList
);
2126 ** Return the bitwise-OR of all Expr.flags fields in the given
2129 u32
sqlite3ExprListFlags(const ExprList
*pList
){
2133 for(i
=0; i
<pList
->nExpr
; i
++){
2134 Expr
*pExpr
= pList
->a
[i
].pExpr
;
2142 ** This is a SELECT-node callback for the expression walker that
2143 ** always "fails". By "fail" in this case, we mean set
2144 ** pWalker->eCode to zero and abort.
2146 ** This callback is used by multiple expression walkers.
2148 int sqlite3SelectWalkFail(Walker
*pWalker
, Select
*NotUsed
){
2149 UNUSED_PARAMETER(NotUsed
);
2155 ** Check the input string to see if it is "true" or "false" (in any case).
2157 ** If the string is.... Return
2159 ** "false" EP_IsFalse
2162 u32
sqlite3IsTrueOrFalse(const char *zIn
){
2163 if( sqlite3StrICmp(zIn
, "true")==0 ) return EP_IsTrue
;
2164 if( sqlite3StrICmp(zIn
, "false")==0 ) return EP_IsFalse
;
2170 ** If the input expression is an ID with the name "true" or "false"
2171 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2172 ** the conversion happened, and zero if the expression is unaltered.
2174 int sqlite3ExprIdToTrueFalse(Expr
*pExpr
){
2176 assert( pExpr
->op
==TK_ID
|| pExpr
->op
==TK_STRING
);
2177 if( !ExprHasProperty(pExpr
, EP_Quoted
|EP_IntValue
)
2178 && (v
= sqlite3IsTrueOrFalse(pExpr
->u
.zToken
))!=0
2180 pExpr
->op
= TK_TRUEFALSE
;
2181 ExprSetProperty(pExpr
, v
);
2188 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2189 ** and 0 if it is FALSE.
2191 int sqlite3ExprTruthValue(const Expr
*pExpr
){
2192 pExpr
= sqlite3ExprSkipCollate((Expr
*)pExpr
);
2193 assert( pExpr
->op
==TK_TRUEFALSE
);
2194 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2195 assert( sqlite3StrICmp(pExpr
->u
.zToken
,"true")==0
2196 || sqlite3StrICmp(pExpr
->u
.zToken
,"false")==0 );
2197 return pExpr
->u
.zToken
[4]==0;
2201 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2202 ** terms that are always true or false. Return the simplified expression.
2203 ** Or return the original expression if no simplification is possible.
2207 ** (x<10) AND true => (x<10)
2208 ** (x<10) AND false => false
2209 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2210 ** (x<10) AND (y=22 OR true) => (x<10)
2211 ** (y=22) OR true => true
2213 Expr
*sqlite3ExprSimplifiedAndOr(Expr
*pExpr
){
2215 if( pExpr
->op
==TK_AND
|| pExpr
->op
==TK_OR
){
2216 Expr
*pRight
= sqlite3ExprSimplifiedAndOr(pExpr
->pRight
);
2217 Expr
*pLeft
= sqlite3ExprSimplifiedAndOr(pExpr
->pLeft
);
2218 if( ExprAlwaysTrue(pLeft
) || ExprAlwaysFalse(pRight
) ){
2219 pExpr
= pExpr
->op
==TK_AND
? pRight
: pLeft
;
2220 }else if( ExprAlwaysTrue(pRight
) || ExprAlwaysFalse(pLeft
) ){
2221 pExpr
= pExpr
->op
==TK_AND
? pLeft
: pRight
;
2229 ** These routines are Walker callbacks used to check expressions to
2230 ** see if they are "constant" for some definition of constant. The
2231 ** Walker.eCode value determines the type of "constant" we are looking
2234 ** These callback routines are used to implement the following:
2236 ** sqlite3ExprIsConstant() pWalker->eCode==1
2237 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2238 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2239 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2241 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2242 ** is found to not be a constant.
2244 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2245 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2246 ** when parsing an existing schema out of the sqlite_schema table and 4
2247 ** when processing a new CREATE TABLE statement. A bound parameter raises
2248 ** an error for new statements, but is silently converted
2249 ** to NULL for existing schemas. This allows sqlite_schema tables that
2250 ** contain a bound parameter because they were generated by older versions
2251 ** of SQLite to be parsed by newer versions of SQLite without raising a
2252 ** malformed schema error.
2254 static int exprNodeIsConstant(Walker
*pWalker
, Expr
*pExpr
){
2256 /* If pWalker->eCode is 2 then any term of the expression that comes from
2257 ** the ON or USING clauses of an outer join disqualifies the expression
2258 ** from being considered constant. */
2259 if( pWalker
->eCode
==2 && ExprHasProperty(pExpr
, EP_OuterON
) ){
2264 switch( pExpr
->op
){
2265 /* Consider functions to be constant if all their arguments are constant
2266 ** and either pWalker->eCode==4 or 5 or the function has the
2267 ** SQLITE_FUNC_CONST flag. */
2269 if( (pWalker
->eCode
>=4 || ExprHasProperty(pExpr
,EP_ConstFunc
))
2270 && !ExprHasProperty(pExpr
, EP_WinFunc
)
2272 if( pWalker
->eCode
==5 ) ExprSetProperty(pExpr
, EP_FromDDL
);
2273 return WRC_Continue
;
2279 /* Convert "true" or "false" in a DEFAULT clause into the
2280 ** appropriate TK_TRUEFALSE operator */
2281 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
2284 /* no break */ deliberate_fall_through
2286 case TK_AGG_FUNCTION
:
2288 testcase( pExpr
->op
==TK_ID
);
2289 testcase( pExpr
->op
==TK_COLUMN
);
2290 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
2291 testcase( pExpr
->op
==TK_AGG_COLUMN
);
2292 if( ExprHasProperty(pExpr
, EP_FixedCol
) && pWalker
->eCode
!=2 ){
2293 return WRC_Continue
;
2295 if( pWalker
->eCode
==3 && pExpr
->iTable
==pWalker
->u
.iCur
){
2296 return WRC_Continue
;
2298 /* no break */ deliberate_fall_through
2299 case TK_IF_NULL_ROW
:
2302 testcase( pExpr
->op
==TK_REGISTER
);
2303 testcase( pExpr
->op
==TK_IF_NULL_ROW
);
2304 testcase( pExpr
->op
==TK_DOT
);
2308 if( pWalker
->eCode
==5 ){
2309 /* Silently convert bound parameters that appear inside of CREATE
2310 ** statements into a NULL when parsing the CREATE statement text out
2311 ** of the sqlite_schema table */
2312 pExpr
->op
= TK_NULL
;
2313 }else if( pWalker
->eCode
==4 ){
2314 /* A bound parameter in a CREATE statement that originates from
2315 ** sqlite3_prepare() causes an error */
2319 /* no break */ deliberate_fall_through
2321 testcase( pExpr
->op
==TK_SELECT
); /* sqlite3SelectWalkFail() disallows */
2322 testcase( pExpr
->op
==TK_EXISTS
); /* sqlite3SelectWalkFail() disallows */
2323 return WRC_Continue
;
2326 static int exprIsConst(Expr
*p
, int initFlag
, int iCur
){
2329 w
.xExprCallback
= exprNodeIsConstant
;
2330 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2332 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2335 sqlite3WalkExpr(&w
, p
);
2340 ** Walk an expression tree. Return non-zero if the expression is constant
2341 ** and 0 if it involves variables or function calls.
2343 ** For the purposes of this function, a double-quoted string (ex: "abc")
2344 ** is considered a variable but a single-quoted string (ex: 'abc') is
2347 int sqlite3ExprIsConstant(Expr
*p
){
2348 return exprIsConst(p
, 1, 0);
2352 ** Walk an expression tree. Return non-zero if
2354 ** (1) the expression is constant, and
2355 ** (2) the expression does originate in the ON or USING clause
2356 ** of a LEFT JOIN, and
2357 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2358 ** operands created by the constant propagation optimization.
2360 ** When this routine returns true, it indicates that the expression
2361 ** can be added to the pParse->pConstExpr list and evaluated once when
2362 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2364 int sqlite3ExprIsConstantNotJoin(Expr
*p
){
2365 return exprIsConst(p
, 2, 0);
2369 ** Walk an expression tree. Return non-zero if the expression is constant
2370 ** for any single row of the table with cursor iCur. In other words, the
2371 ** expression must not refer to any non-deterministic function nor any
2372 ** table other than iCur.
2374 int sqlite3ExprIsTableConstant(Expr
*p
, int iCur
){
2375 return exprIsConst(p
, 3, iCur
);
2379 ** Check pExpr to see if it is an invariant constraint on data source pSrc.
2380 ** This is an optimization. False negatives will perhaps cause slower
2381 ** queries, but false positives will yield incorrect answers. So when in
2384 ** To be an invariant constraint, the following must be true:
2386 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2388 ** (2) pExpr cannot use subqueries or non-deterministic functions.
2390 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2391 ** (Is there some way to relax this constraint?)
2393 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2394 ** (4a) pExpr must come from an ON clause..
2395 (4b) and specifically the ON clause associated with the LEFT JOIN.
2397 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2398 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2399 ** clause, not an ON clause.
2401 int sqlite3ExprIsTableConstraint(Expr
*pExpr
, const SrcItem
*pSrc
){
2402 if( pSrc
->fg
.jointype
& JT_LTORJ
){
2403 return 0; /* rule (3) */
2405 if( pSrc
->fg
.jointype
& JT_LEFT
){
2406 if( !ExprHasProperty(pExpr
, EP_OuterON
) ) return 0; /* rule (4a) */
2407 if( pExpr
->w
.iJoin
!=pSrc
->iCursor
) return 0; /* rule (4b) */
2409 if( ExprHasProperty(pExpr
, EP_OuterON
) ) return 0; /* rule (5) */
2411 return sqlite3ExprIsTableConstant(pExpr
, pSrc
->iCursor
); /* rules (1), (2) */
2416 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2418 static int exprNodeIsConstantOrGroupBy(Walker
*pWalker
, Expr
*pExpr
){
2419 ExprList
*pGroupBy
= pWalker
->u
.pGroupBy
;
2422 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2424 for(i
=0; i
<pGroupBy
->nExpr
; i
++){
2425 Expr
*p
= pGroupBy
->a
[i
].pExpr
;
2426 if( sqlite3ExprCompare(0, pExpr
, p
, -1)<2 ){
2427 CollSeq
*pColl
= sqlite3ExprNNCollSeq(pWalker
->pParse
, p
);
2428 if( sqlite3IsBinary(pColl
) ){
2434 /* Check if pExpr is a sub-select. If so, consider it variable. */
2435 if( ExprUseXSelect(pExpr
) ){
2440 return exprNodeIsConstant(pWalker
, pExpr
);
2444 ** Walk the expression tree passed as the first argument. Return non-zero
2445 ** if the expression consists entirely of constants or copies of terms
2446 ** in pGroupBy that sort with the BINARY collation sequence.
2448 ** This routine is used to determine if a term of the HAVING clause can
2449 ** be promoted into the WHERE clause. In order for such a promotion to work,
2450 ** the value of the HAVING clause term must be the same for all members of
2451 ** a "group". The requirement that the GROUP BY term must be BINARY
2452 ** assumes that no other collating sequence will have a finer-grained
2453 ** grouping than binary. In other words (A=B COLLATE binary) implies
2454 ** A=B in every other collating sequence. The requirement that the
2455 ** GROUP BY be BINARY is stricter than necessary. It would also work
2456 ** to promote HAVING clauses that use the same alternative collating
2457 ** sequence as the GROUP BY term, but that is much harder to check,
2458 ** alternative collating sequences are uncommon, and this is only an
2459 ** optimization, so we take the easy way out and simply require the
2460 ** GROUP BY to use the BINARY collating sequence.
2462 int sqlite3ExprIsConstantOrGroupBy(Parse
*pParse
, Expr
*p
, ExprList
*pGroupBy
){
2465 w
.xExprCallback
= exprNodeIsConstantOrGroupBy
;
2466 w
.xSelectCallback
= 0;
2467 w
.u
.pGroupBy
= pGroupBy
;
2469 sqlite3WalkExpr(&w
, p
);
2474 ** Walk an expression tree for the DEFAULT field of a column definition
2475 ** in a CREATE TABLE statement. Return non-zero if the expression is
2476 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2477 ** the expression is constant or a function call with constant arguments.
2478 ** Return and 0 if there are any variables.
2480 ** isInit is true when parsing from sqlite_schema. isInit is false when
2481 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2482 ** (such as ? or $abc) in the expression are converted into NULL. When
2483 ** isInit is false, parameters raise an error. Parameters should not be
2484 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2485 ** allowed it, so we need to support it when reading sqlite_schema for
2486 ** backwards compatibility.
2488 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2490 ** For the purposes of this function, a double-quoted string (ex: "abc")
2491 ** is considered a variable but a single-quoted string (ex: 'abc') is
2494 int sqlite3ExprIsConstantOrFunction(Expr
*p
, u8 isInit
){
2495 assert( isInit
==0 || isInit
==1 );
2496 return exprIsConst(p
, 4+isInit
, 0);
2499 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2501 ** Walk an expression tree. Return 1 if the expression contains a
2502 ** subquery of some kind. Return 0 if there are no subqueries.
2504 int sqlite3ExprContainsSubquery(Expr
*p
){
2507 w
.xExprCallback
= sqlite3ExprWalkNoop
;
2508 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2510 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2512 sqlite3WalkExpr(&w
, p
);
2518 ** If the expression p codes a constant integer that is small enough
2519 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2520 ** in *pValue. If the expression is not an integer or if it is too big
2521 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2523 int sqlite3ExprIsInteger(const Expr
*p
, int *pValue
){
2525 if( NEVER(p
==0) ) return 0; /* Used to only happen following on OOM */
2527 /* If an expression is an integer literal that fits in a signed 32-bit
2528 ** integer, then the EP_IntValue flag will have already been set */
2529 assert( p
->op
!=TK_INTEGER
|| (p
->flags
& EP_IntValue
)!=0
2530 || sqlite3GetInt32(p
->u
.zToken
, &rc
)==0 );
2532 if( p
->flags
& EP_IntValue
){
2533 *pValue
= p
->u
.iValue
;
2538 rc
= sqlite3ExprIsInteger(p
->pLeft
, pValue
);
2543 if( sqlite3ExprIsInteger(p
->pLeft
, &v
) ){
2544 assert( ((unsigned int)v
)!=0x80000000 );
2556 ** Return FALSE if there is no chance that the expression can be NULL.
2558 ** If the expression might be NULL or if the expression is too complex
2559 ** to tell return TRUE.
2561 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2562 ** when we know that a value cannot be NULL. Hence, a false positive
2563 ** (returning TRUE when in fact the expression can never be NULL) might
2564 ** be a small performance hit but is otherwise harmless. On the other
2565 ** hand, a false negative (returning FALSE when the result could be NULL)
2566 ** will likely result in an incorrect answer. So when in doubt, return
2569 int sqlite3ExprCanBeNull(const Expr
*p
){
2572 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){
2577 if( op
==TK_REGISTER
) op
= p
->op2
;
2585 assert( ExprUseYTab(p
) );
2586 return ExprHasProperty(p
, EP_CanBeNull
) ||
2587 p
->y
.pTab
==0 || /* Reference to column of index on expression */
2589 && p
->y
.pTab
->aCol
!=0 /* Possible due to prior error */
2590 && p
->y
.pTab
->aCol
[p
->iColumn
].notNull
==0);
2597 ** Return TRUE if the given expression is a constant which would be
2598 ** unchanged by OP_Affinity with the affinity given in the second
2601 ** This routine is used to determine if the OP_Affinity operation
2602 ** can be omitted. When in doubt return FALSE. A false negative
2603 ** is harmless. A false positive, however, can result in the wrong
2606 int sqlite3ExprNeedsNoAffinityChange(const Expr
*p
, char aff
){
2609 if( aff
==SQLITE_AFF_BLOB
) return 1;
2610 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){
2611 if( p
->op
==TK_UMINUS
) unaryMinus
= 1;
2615 if( op
==TK_REGISTER
) op
= p
->op2
;
2618 return aff
>=SQLITE_AFF_NUMERIC
;
2621 return aff
>=SQLITE_AFF_NUMERIC
;
2624 return !unaryMinus
&& aff
==SQLITE_AFF_TEXT
;
2630 assert( p
->iTable
>=0 ); /* p cannot be part of a CHECK constraint */
2631 return aff
>=SQLITE_AFF_NUMERIC
&& p
->iColumn
<0;
2640 ** Return TRUE if the given string is a row-id column name.
2642 int sqlite3IsRowid(const char *z
){
2643 if( sqlite3StrICmp(z
, "_ROWID_")==0 ) return 1;
2644 if( sqlite3StrICmp(z
, "ROWID")==0 ) return 1;
2645 if( sqlite3StrICmp(z
, "OID")==0 ) return 1;
2650 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2651 ** that can be simplified to a direct table access, then return
2652 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2653 ** or if the SELECT statement needs to be manifested into a transient
2654 ** table, then return NULL.
2656 #ifndef SQLITE_OMIT_SUBQUERY
2657 static Select
*isCandidateForInOpt(const Expr
*pX
){
2663 if( !ExprUseXSelect(pX
) ) return 0; /* Not a subquery */
2664 if( ExprHasProperty(pX
, EP_VarSelect
) ) return 0; /* Correlated subq */
2666 if( p
->pPrior
) return 0; /* Not a compound SELECT */
2667 if( p
->selFlags
& (SF_Distinct
|SF_Aggregate
) ){
2668 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Distinct
);
2669 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Aggregate
);
2670 return 0; /* No DISTINCT keyword and no aggregate functions */
2672 assert( p
->pGroupBy
==0 ); /* Has no GROUP BY clause */
2673 if( p
->pLimit
) return 0; /* Has no LIMIT clause */
2674 if( p
->pWhere
) return 0; /* Has no WHERE clause */
2677 if( pSrc
->nSrc
!=1 ) return 0; /* Single term in FROM clause */
2678 if( pSrc
->a
[0].pSelect
) return 0; /* FROM is not a subquery or view */
2679 pTab
= pSrc
->a
[0].pTab
;
2681 assert( !IsView(pTab
) ); /* FROM clause is not a view */
2682 if( IsVirtual(pTab
) ) return 0; /* FROM clause not a virtual table */
2684 assert( pEList
!=0 );
2685 /* All SELECT results must be columns. */
2686 for(i
=0; i
<pEList
->nExpr
; i
++){
2687 Expr
*pRes
= pEList
->a
[i
].pExpr
;
2688 if( pRes
->op
!=TK_COLUMN
) return 0;
2689 assert( pRes
->iTable
==pSrc
->a
[0].iCursor
); /* Not a correlated subquery */
2693 #endif /* SQLITE_OMIT_SUBQUERY */
2695 #ifndef SQLITE_OMIT_SUBQUERY
2697 ** Generate code that checks the left-most column of index table iCur to see if
2698 ** it contains any NULL entries. Cause the register at regHasNull to be set
2699 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2700 ** to be set to NULL if iCur contains one or more NULL values.
2702 static void sqlite3SetHasNullFlag(Vdbe
*v
, int iCur
, int regHasNull
){
2704 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regHasNull
);
2705 addr1
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iCur
); VdbeCoverage(v
);
2706 sqlite3VdbeAddOp3(v
, OP_Column
, iCur
, 0, regHasNull
);
2707 sqlite3VdbeChangeP5(v
, OPFLAG_TYPEOFARG
);
2708 VdbeComment((v
, "first_entry_in(%d)", iCur
));
2709 sqlite3VdbeJumpHere(v
, addr1
);
2714 #ifndef SQLITE_OMIT_SUBQUERY
2716 ** The argument is an IN operator with a list (not a subquery) on the
2717 ** right-hand side. Return TRUE if that list is constant.
2719 static int sqlite3InRhsIsConstant(Expr
*pIn
){
2722 assert( !ExprHasProperty(pIn
, EP_xIsSelect
) );
2725 res
= sqlite3ExprIsConstant(pIn
);
2732 ** This function is used by the implementation of the IN (...) operator.
2733 ** The pX parameter is the expression on the RHS of the IN operator, which
2734 ** might be either a list of expressions or a subquery.
2736 ** The job of this routine is to find or create a b-tree object that can
2737 ** be used either to test for membership in the RHS set or to iterate through
2738 ** all members of the RHS set, skipping duplicates.
2740 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2741 ** and the *piTab parameter is set to the index of that cursor.
2743 ** The returned value of this function indicates the b-tree type, as follows:
2745 ** IN_INDEX_ROWID - The cursor was opened on a database table.
2746 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2747 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2748 ** IN_INDEX_EPH - The cursor was opened on a specially created and
2749 ** populated epheremal table.
2750 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2751 ** implemented as a sequence of comparisons.
2753 ** An existing b-tree might be used if the RHS expression pX is a simple
2754 ** subquery such as:
2756 ** SELECT <column1>, <column2>... FROM <table>
2758 ** If the RHS of the IN operator is a list or a more complex subquery, then
2759 ** an ephemeral table might need to be generated from the RHS and then
2760 ** pX->iTable made to point to the ephemeral table instead of an
2761 ** existing table. In this case, the creation and initialization of the
2762 ** ephmeral table might be put inside of a subroutine, the EP_Subrtn flag
2763 ** will be set on pX and the pX->y.sub fields will be set to show where
2764 ** the subroutine is coded.
2766 ** The inFlags parameter must contain, at a minimum, one of the bits
2767 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2768 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2769 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2770 ** be used to loop over all values of the RHS of the IN operator.
2772 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2773 ** through the set members) then the b-tree must not contain duplicates.
2774 ** An epheremal table will be created unless the selected columns are guaranteed
2775 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2776 ** a UNIQUE constraint or index.
2778 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2779 ** for fast set membership tests) then an epheremal table must
2780 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2781 ** index can be found with the specified <columns> as its left-most.
2783 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2784 ** if the RHS of the IN operator is a list (not a subquery) then this
2785 ** routine might decide that creating an ephemeral b-tree for membership
2786 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2787 ** calling routine should implement the IN operator using a sequence
2788 ** of Eq or Ne comparison operations.
2790 ** When the b-tree is being used for membership tests, the calling function
2791 ** might need to know whether or not the RHS side of the IN operator
2792 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
2793 ** if there is any chance that the (...) might contain a NULL value at
2794 ** runtime, then a register is allocated and the register number written
2795 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2796 ** NULL value, then *prRhsHasNull is left unchanged.
2798 ** If a register is allocated and its location stored in *prRhsHasNull, then
2799 ** the value in that register will be NULL if the b-tree contains one or more
2800 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2803 ** If the aiMap parameter is not NULL, it must point to an array containing
2804 ** one element for each column returned by the SELECT statement on the RHS
2805 ** of the IN(...) operator. The i'th entry of the array is populated with the
2806 ** offset of the index column that matches the i'th column returned by the
2807 ** SELECT. For example, if the expression and selected index are:
2809 ** (?,?,?) IN (SELECT a, b, c FROM t1)
2810 ** CREATE INDEX i1 ON t1(b, c, a);
2812 ** then aiMap[] is populated with {2, 0, 1}.
2814 #ifndef SQLITE_OMIT_SUBQUERY
2815 int sqlite3FindInIndex(
2816 Parse
*pParse
, /* Parsing context */
2817 Expr
*pX
, /* The IN expression */
2818 u32 inFlags
, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2819 int *prRhsHasNull
, /* Register holding NULL status. See notes */
2820 int *aiMap
, /* Mapping from Index fields to RHS fields */
2821 int *piTab
/* OUT: index to use */
2823 Select
*p
; /* SELECT to the right of IN operator */
2824 int eType
= 0; /* Type of RHS table. IN_INDEX_* */
2825 int iTab
; /* Cursor of the RHS table */
2826 int mustBeUnique
; /* True if RHS must be unique */
2827 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Virtual machine being coded */
2829 assert( pX
->op
==TK_IN
);
2830 mustBeUnique
= (inFlags
& IN_INDEX_LOOP
)!=0;
2831 iTab
= pParse
->nTab
++;
2833 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2834 ** whether or not the SELECT result contains NULL values, check whether
2835 ** or not NULL is actually possible (it may not be, for example, due
2836 ** to NOT NULL constraints in the schema). If no NULL values are possible,
2837 ** set prRhsHasNull to 0 before continuing. */
2838 if( prRhsHasNull
&& ExprUseXSelect(pX
) ){
2840 ExprList
*pEList
= pX
->x
.pSelect
->pEList
;
2841 for(i
=0; i
<pEList
->nExpr
; i
++){
2842 if( sqlite3ExprCanBeNull(pEList
->a
[i
].pExpr
) ) break;
2844 if( i
==pEList
->nExpr
){
2849 /* Check to see if an existing table or index can be used to
2850 ** satisfy the query. This is preferable to generating a new
2851 ** ephemeral table. */
2852 if( pParse
->nErr
==0 && (p
= isCandidateForInOpt(pX
))!=0 ){
2853 sqlite3
*db
= pParse
->db
; /* Database connection */
2854 Table
*pTab
; /* Table <table>. */
2855 int iDb
; /* Database idx for pTab */
2856 ExprList
*pEList
= p
->pEList
;
2857 int nExpr
= pEList
->nExpr
;
2859 assert( p
->pEList
!=0 ); /* Because of isCandidateForInOpt(p) */
2860 assert( p
->pEList
->a
[0].pExpr
!=0 ); /* Because of isCandidateForInOpt(p) */
2861 assert( p
->pSrc
!=0 ); /* Because of isCandidateForInOpt(p) */
2862 pTab
= p
->pSrc
->a
[0].pTab
;
2864 /* Code an OP_Transaction and OP_TableLock for <table>. */
2865 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
2866 assert( iDb
>=0 && iDb
<SQLITE_MAX_DB
);
2867 sqlite3CodeVerifySchema(pParse
, iDb
);
2868 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 0, pTab
->zName
);
2870 assert(v
); /* sqlite3GetVdbe() has always been previously called */
2871 if( nExpr
==1 && pEList
->a
[0].pExpr
->iColumn
<0 ){
2872 /* The "x IN (SELECT rowid FROM table)" case */
2873 int iAddr
= sqlite3VdbeAddOp0(v
, OP_Once
);
2876 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
2877 eType
= IN_INDEX_ROWID
;
2878 ExplainQueryPlan((pParse
, 0,
2879 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab
->zName
));
2880 sqlite3VdbeJumpHere(v
, iAddr
);
2882 Index
*pIdx
; /* Iterator variable */
2883 int affinity_ok
= 1;
2886 /* Check that the affinity that will be used to perform each
2887 ** comparison is the same as the affinity of each column in table
2888 ** on the RHS of the IN operator. If it not, it is not possible to
2889 ** use any index of the RHS table. */
2890 for(i
=0; i
<nExpr
&& affinity_ok
; i
++){
2891 Expr
*pLhs
= sqlite3VectorFieldSubexpr(pX
->pLeft
, i
);
2892 int iCol
= pEList
->a
[i
].pExpr
->iColumn
;
2893 char idxaff
= sqlite3TableColumnAffinity(pTab
,iCol
); /* RHS table */
2894 char cmpaff
= sqlite3CompareAffinity(pLhs
, idxaff
);
2895 testcase( cmpaff
==SQLITE_AFF_BLOB
);
2896 testcase( cmpaff
==SQLITE_AFF_TEXT
);
2898 case SQLITE_AFF_BLOB
:
2900 case SQLITE_AFF_TEXT
:
2901 /* sqlite3CompareAffinity() only returns TEXT if one side or the
2902 ** other has no affinity and the other side is TEXT. Hence,
2903 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2904 ** and for the term on the LHS of the IN to have no affinity. */
2905 assert( idxaff
==SQLITE_AFF_TEXT
);
2908 affinity_ok
= sqlite3IsNumericAffinity(idxaff
);
2913 /* Search for an existing index that will work for this IN operator */
2914 for(pIdx
=pTab
->pIndex
; pIdx
&& eType
==0; pIdx
=pIdx
->pNext
){
2915 Bitmask colUsed
; /* Columns of the index used */
2916 Bitmask mCol
; /* Mask for the current column */
2917 if( pIdx
->nColumn
<nExpr
) continue;
2918 if( pIdx
->pPartIdxWhere
!=0 ) continue;
2919 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2920 ** BITMASK(nExpr) without overflowing */
2921 testcase( pIdx
->nColumn
==BMS
-2 );
2922 testcase( pIdx
->nColumn
==BMS
-1 );
2923 if( pIdx
->nColumn
>=BMS
-1 ) continue;
2925 if( pIdx
->nKeyCol
>nExpr
2926 ||(pIdx
->nColumn
>nExpr
&& !IsUniqueIndex(pIdx
))
2928 continue; /* This index is not unique over the IN RHS columns */
2932 colUsed
= 0; /* Columns of index used so far */
2933 for(i
=0; i
<nExpr
; i
++){
2934 Expr
*pLhs
= sqlite3VectorFieldSubexpr(pX
->pLeft
, i
);
2935 Expr
*pRhs
= pEList
->a
[i
].pExpr
;
2936 CollSeq
*pReq
= sqlite3BinaryCompareCollSeq(pParse
, pLhs
, pRhs
);
2939 assert( pReq
!=0 || pRhs
->iColumn
==XN_ROWID
|| pParse
->nErr
);
2940 for(j
=0; j
<nExpr
; j
++){
2941 if( pIdx
->aiColumn
[j
]!=pRhs
->iColumn
) continue;
2942 assert( pIdx
->azColl
[j
] );
2943 if( pReq
!=0 && sqlite3StrICmp(pReq
->zName
, pIdx
->azColl
[j
])!=0 ){
2948 if( j
==nExpr
) break;
2950 if( mCol
& colUsed
) break; /* Each column used only once */
2952 if( aiMap
) aiMap
[i
] = j
;
2955 assert( i
==nExpr
|| colUsed
!=(MASKBIT(nExpr
)-1) );
2956 if( colUsed
==(MASKBIT(nExpr
)-1) ){
2957 /* If we reach this point, that means the index pIdx is usable */
2958 int iAddr
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
2959 ExplainQueryPlan((pParse
, 0,
2960 "USING INDEX %s FOR IN-OPERATOR",pIdx
->zName
));
2961 sqlite3VdbeAddOp3(v
, OP_OpenRead
, iTab
, pIdx
->tnum
, iDb
);
2962 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
2963 VdbeComment((v
, "%s", pIdx
->zName
));
2964 assert( IN_INDEX_INDEX_DESC
== IN_INDEX_INDEX_ASC
+1 );
2965 eType
= IN_INDEX_INDEX_ASC
+ pIdx
->aSortOrder
[0];
2968 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
2969 i64 mask
= (1<<nExpr
)-1;
2970 sqlite3VdbeAddOp4Dup8(v
, OP_ColumnsUsed
,
2971 iTab
, 0, 0, (u8
*)&mask
, P4_INT64
);
2973 *prRhsHasNull
= ++pParse
->nMem
;
2975 sqlite3SetHasNullFlag(v
, iTab
, *prRhsHasNull
);
2978 sqlite3VdbeJumpHere(v
, iAddr
);
2980 } /* End loop over indexes */
2981 } /* End if( affinity_ok ) */
2982 } /* End if not an rowid index */
2983 } /* End attempt to optimize using an index */
2985 /* If no preexisting index is available for the IN clause
2986 ** and IN_INDEX_NOOP is an allowed reply
2987 ** and the RHS of the IN operator is a list, not a subquery
2988 ** and the RHS is not constant or has two or fewer terms,
2989 ** then it is not worth creating an ephemeral table to evaluate
2990 ** the IN operator so return IN_INDEX_NOOP.
2993 && (inFlags
& IN_INDEX_NOOP_OK
)
2995 && (!sqlite3InRhsIsConstant(pX
) || pX
->x
.pList
->nExpr
<=2)
2997 pParse
->nTab
--; /* Back out the allocation of the unused cursor */
2998 iTab
= -1; /* Cursor is not allocated */
2999 eType
= IN_INDEX_NOOP
;
3003 /* Could not find an existing table or index to use as the RHS b-tree.
3004 ** We will have to generate an ephemeral table to do the job.
3006 u32 savedNQueryLoop
= pParse
->nQueryLoop
;
3007 int rMayHaveNull
= 0;
3008 eType
= IN_INDEX_EPH
;
3009 if( inFlags
& IN_INDEX_LOOP
){
3010 pParse
->nQueryLoop
= 0;
3011 }else if( prRhsHasNull
){
3012 *prRhsHasNull
= rMayHaveNull
= ++pParse
->nMem
;
3014 assert( pX
->op
==TK_IN
);
3015 sqlite3CodeRhsOfIN(pParse
, pX
, iTab
);
3017 sqlite3SetHasNullFlag(v
, iTab
, rMayHaveNull
);
3019 pParse
->nQueryLoop
= savedNQueryLoop
;
3022 if( aiMap
&& eType
!=IN_INDEX_INDEX_ASC
&& eType
!=IN_INDEX_INDEX_DESC
){
3024 n
= sqlite3ExprVectorSize(pX
->pLeft
);
3025 for(i
=0; i
<n
; i
++) aiMap
[i
] = i
;
3032 #ifndef SQLITE_OMIT_SUBQUERY
3034 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3035 ** function allocates and returns a nul-terminated string containing
3036 ** the affinities to be used for each column of the comparison.
3038 ** It is the responsibility of the caller to ensure that the returned
3039 ** string is eventually freed using sqlite3DbFree().
3041 static char *exprINAffinity(Parse
*pParse
, const Expr
*pExpr
){
3042 Expr
*pLeft
= pExpr
->pLeft
;
3043 int nVal
= sqlite3ExprVectorSize(pLeft
);
3044 Select
*pSelect
= ExprUseXSelect(pExpr
) ? pExpr
->x
.pSelect
: 0;
3047 assert( pExpr
->op
==TK_IN
);
3048 zRet
= sqlite3DbMallocRaw(pParse
->db
, nVal
+1);
3051 for(i
=0; i
<nVal
; i
++){
3052 Expr
*pA
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3053 char a
= sqlite3ExprAffinity(pA
);
3055 zRet
[i
] = sqlite3CompareAffinity(pSelect
->pEList
->a
[i
].pExpr
, a
);
3066 #ifndef SQLITE_OMIT_SUBQUERY
3068 ** Load the Parse object passed as the first argument with an error
3069 ** message of the form:
3071 ** "sub-select returns N columns - expected M"
3073 void sqlite3SubselectError(Parse
*pParse
, int nActual
, int nExpect
){
3074 if( pParse
->nErr
==0 ){
3075 const char *zFmt
= "sub-select returns %d columns - expected %d";
3076 sqlite3ErrorMsg(pParse
, zFmt
, nActual
, nExpect
);
3082 ** Expression pExpr is a vector that has been used in a context where
3083 ** it is not permitted. If pExpr is a sub-select vector, this routine
3084 ** loads the Parse object with a message of the form:
3086 ** "sub-select returns N columns - expected 1"
3088 ** Or, if it is a regular scalar vector:
3090 ** "row value misused"
3092 void sqlite3VectorErrorMsg(Parse
*pParse
, Expr
*pExpr
){
3093 #ifndef SQLITE_OMIT_SUBQUERY
3094 if( ExprUseXSelect(pExpr
) ){
3095 sqlite3SubselectError(pParse
, pExpr
->x
.pSelect
->pEList
->nExpr
, 1);
3099 sqlite3ErrorMsg(pParse
, "row value misused");
3103 #ifndef SQLITE_OMIT_SUBQUERY
3105 ** Generate code that will construct an ephemeral table containing all terms
3106 ** in the RHS of an IN operator. The IN operator can be in either of two
3109 ** x IN (4,5,11) -- IN operator with list on right-hand side
3110 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3112 ** The pExpr parameter is the IN operator. The cursor number for the
3113 ** constructed ephermeral table is returned. The first time the ephemeral
3114 ** table is computed, the cursor number is also stored in pExpr->iTable,
3115 ** however the cursor number returned might not be the same, as it might
3116 ** have been duplicated using OP_OpenDup.
3118 ** If the LHS expression ("x" in the examples) is a column value, or
3119 ** the SELECT statement returns a column value, then the affinity of that
3120 ** column is used to build the index keys. If both 'x' and the
3121 ** SELECT... statement are columns, then numeric affinity is used
3122 ** if either column has NUMERIC or INTEGER affinity. If neither
3123 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3126 void sqlite3CodeRhsOfIN(
3127 Parse
*pParse
, /* Parsing context */
3128 Expr
*pExpr
, /* The IN operator */
3129 int iTab
/* Use this cursor number */
3131 int addrOnce
= 0; /* Address of the OP_Once instruction at top */
3132 int addr
; /* Address of OP_OpenEphemeral instruction */
3133 Expr
*pLeft
; /* the LHS of the IN operator */
3134 KeyInfo
*pKeyInfo
= 0; /* Key information */
3135 int nVal
; /* Size of vector pLeft */
3136 Vdbe
*v
; /* The prepared statement under construction */
3141 /* The evaluation of the IN must be repeated every time it
3142 ** is encountered if any of the following is true:
3144 ** * The right-hand side is a correlated subquery
3145 ** * The right-hand side is an expression list containing variables
3146 ** * We are inside a trigger
3148 ** If all of the above are false, then we can compute the RHS just once
3149 ** and reuse it many names.
3151 if( !ExprHasProperty(pExpr
, EP_VarSelect
) && pParse
->iSelfTab
==0 ){
3152 /* Reuse of the RHS is allowed */
3153 /* If this routine has already been coded, but the previous code
3154 ** might not have been invoked yet, so invoke it now as a subroutine.
3156 if( ExprHasProperty(pExpr
, EP_Subrtn
) ){
3157 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3158 if( ExprUseXSelect(pExpr
) ){
3159 ExplainQueryPlan((pParse
, 0, "REUSE LIST SUBQUERY %d",
3160 pExpr
->x
.pSelect
->selId
));
3162 assert( ExprUseYSub(pExpr
) );
3163 sqlite3VdbeAddOp2(v
, OP_Gosub
, pExpr
->y
.sub
.regReturn
,
3164 pExpr
->y
.sub
.iAddr
);
3165 assert( iTab
!=pExpr
->iTable
);
3166 sqlite3VdbeAddOp2(v
, OP_OpenDup
, iTab
, pExpr
->iTable
);
3167 sqlite3VdbeJumpHere(v
, addrOnce
);
3171 /* Begin coding the subroutine */
3172 assert( !ExprUseYWin(pExpr
) );
3173 ExprSetProperty(pExpr
, EP_Subrtn
);
3174 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
3175 pExpr
->y
.sub
.regReturn
= ++pParse
->nMem
;
3176 pExpr
->y
.sub
.iAddr
=
3177 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pExpr
->y
.sub
.regReturn
) + 1;
3179 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3182 /* Check to see if this is a vector IN operator */
3183 pLeft
= pExpr
->pLeft
;
3184 nVal
= sqlite3ExprVectorSize(pLeft
);
3186 /* Construct the ephemeral table that will contain the content of
3187 ** RHS of the IN operator.
3189 pExpr
->iTable
= iTab
;
3190 addr
= sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pExpr
->iTable
, nVal
);
3191 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3192 if( ExprUseXSelect(pExpr
) ){
3193 VdbeComment((v
, "Result of SELECT %u", pExpr
->x
.pSelect
->selId
));
3195 VdbeComment((v
, "RHS of IN operator"));
3198 pKeyInfo
= sqlite3KeyInfoAlloc(pParse
->db
, nVal
, 1);
3200 if( ExprUseXSelect(pExpr
) ){
3201 /* Case 1: expr IN (SELECT ...)
3203 ** Generate code to write the results of the select into the temporary
3204 ** table allocated and opened above.
3206 Select
*pSelect
= pExpr
->x
.pSelect
;
3207 ExprList
*pEList
= pSelect
->pEList
;
3209 ExplainQueryPlan((pParse
, 1, "%sLIST SUBQUERY %d",
3210 addrOnce
?"":"CORRELATED ", pSelect
->selId
3212 /* If the LHS and RHS of the IN operator do not match, that
3213 ** error will have been caught long before we reach this point. */
3214 if( ALWAYS(pEList
->nExpr
==nVal
) ){
3219 sqlite3SelectDestInit(&dest
, SRT_Set
, iTab
);
3220 dest
.zAffSdst
= exprINAffinity(pParse
, pExpr
);
3221 pSelect
->iLimit
= 0;
3222 testcase( pSelect
->selFlags
& SF_Distinct
);
3223 testcase( pKeyInfo
==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3224 pCopy
= sqlite3SelectDup(pParse
->db
, pSelect
, 0);
3225 rc
= pParse
->db
->mallocFailed
? 1 :sqlite3Select(pParse
, pCopy
, &dest
);
3226 sqlite3SelectDelete(pParse
->db
, pCopy
);
3227 sqlite3DbFree(pParse
->db
, dest
.zAffSdst
);
3229 sqlite3KeyInfoUnref(pKeyInfo
);
3232 assert( pKeyInfo
!=0 ); /* OOM will cause exit after sqlite3Select() */
3233 assert( pEList
!=0 );
3234 assert( pEList
->nExpr
>0 );
3235 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
3236 for(i
=0; i
<nVal
; i
++){
3237 Expr
*p
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3238 pKeyInfo
->aColl
[i
] = sqlite3BinaryCompareCollSeq(
3239 pParse
, p
, pEList
->a
[i
].pExpr
3243 }else if( ALWAYS(pExpr
->x
.pList
!=0) ){
3244 /* Case 2: expr IN (exprlist)
3246 ** For each expression, build an index key from the evaluation and
3247 ** store it in the temporary table. If <expr> is a column, then use
3248 ** that columns affinity when building index keys. If <expr> is not
3249 ** a column, use numeric affinity.
3251 char affinity
; /* Affinity of the LHS of the IN */
3253 ExprList
*pList
= pExpr
->x
.pList
;
3254 struct ExprList_item
*pItem
;
3256 affinity
= sqlite3ExprAffinity(pLeft
);
3257 if( affinity
<=SQLITE_AFF_NONE
){
3258 affinity
= SQLITE_AFF_BLOB
;
3259 }else if( affinity
==SQLITE_AFF_REAL
){
3260 affinity
= SQLITE_AFF_NUMERIC
;
3263 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
3264 pKeyInfo
->aColl
[0] = sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
3267 /* Loop through each expression in <exprlist>. */
3268 r1
= sqlite3GetTempReg(pParse
);
3269 r2
= sqlite3GetTempReg(pParse
);
3270 for(i
=pList
->nExpr
, pItem
=pList
->a
; i
>0; i
--, pItem
++){
3271 Expr
*pE2
= pItem
->pExpr
;
3273 /* If the expression is not constant then we will need to
3274 ** disable the test that was generated above that makes sure
3275 ** this code only executes once. Because for a non-constant
3276 ** expression we need to rerun this code each time.
3278 if( addrOnce
&& !sqlite3ExprIsConstant(pE2
) ){
3279 sqlite3VdbeChangeToNoop(v
, addrOnce
-1);
3280 sqlite3VdbeChangeToNoop(v
, addrOnce
);
3281 ExprClearProperty(pExpr
, EP_Subrtn
);
3285 /* Evaluate the expression and insert it into the temp table */
3286 sqlite3ExprCode(pParse
, pE2
, r1
);
3287 sqlite3VdbeAddOp4(v
, OP_MakeRecord
, r1
, 1, r2
, &affinity
, 1);
3288 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, iTab
, r2
, r1
, 1);
3290 sqlite3ReleaseTempReg(pParse
, r1
);
3291 sqlite3ReleaseTempReg(pParse
, r2
);
3294 sqlite3VdbeChangeP4(v
, addr
, (void *)pKeyInfo
, P4_KEYINFO
);
3297 sqlite3VdbeAddOp1(v
, OP_NullRow
, iTab
);
3298 sqlite3VdbeJumpHere(v
, addrOnce
);
3299 /* Subroutine return */
3300 assert( ExprUseYSub(pExpr
) );
3301 assert( sqlite3VdbeGetOp(v
,pExpr
->y
.sub
.iAddr
-1)->opcode
==OP_BeginSubrtn
3303 sqlite3VdbeAddOp3(v
, OP_Return
, pExpr
->y
.sub
.regReturn
,
3304 pExpr
->y
.sub
.iAddr
, 1);
3306 sqlite3ClearTempRegCache(pParse
);
3309 #endif /* SQLITE_OMIT_SUBQUERY */
3312 ** Generate code for scalar subqueries used as a subquery expression
3313 ** or EXISTS operator:
3315 ** (SELECT a FROM b) -- subquery
3316 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3318 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3320 ** Return the register that holds the result. For a multi-column SELECT,
3321 ** the result is stored in a contiguous array of registers and the
3322 ** return value is the register of the left-most result column.
3323 ** Return 0 if an error occurs.
3325 #ifndef SQLITE_OMIT_SUBQUERY
3326 int sqlite3CodeSubselect(Parse
*pParse
, Expr
*pExpr
){
3327 int addrOnce
= 0; /* Address of OP_Once at top of subroutine */
3328 int rReg
= 0; /* Register storing resulting */
3329 Select
*pSel
; /* SELECT statement to encode */
3330 SelectDest dest
; /* How to deal with SELECT result */
3331 int nReg
; /* Registers to allocate */
3332 Expr
*pLimit
; /* New limit expression */
3333 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3334 int addrExplain
; /* Address of OP_Explain instruction */
3337 Vdbe
*v
= pParse
->pVdbe
;
3339 if( pParse
->nErr
) return 0;
3340 testcase( pExpr
->op
==TK_EXISTS
);
3341 testcase( pExpr
->op
==TK_SELECT
);
3342 assert( pExpr
->op
==TK_EXISTS
|| pExpr
->op
==TK_SELECT
);
3343 assert( ExprUseXSelect(pExpr
) );
3344 pSel
= pExpr
->x
.pSelect
;
3346 /* If this routine has already been coded, then invoke it as a
3348 if( ExprHasProperty(pExpr
, EP_Subrtn
) ){
3349 ExplainQueryPlan((pParse
, 0, "REUSE SUBQUERY %d", pSel
->selId
));
3350 assert( ExprUseYSub(pExpr
) );
3351 sqlite3VdbeAddOp2(v
, OP_Gosub
, pExpr
->y
.sub
.regReturn
,
3352 pExpr
->y
.sub
.iAddr
);
3353 return pExpr
->iTable
;
3356 /* Begin coding the subroutine */
3357 assert( !ExprUseYWin(pExpr
) );
3358 assert( !ExprHasProperty(pExpr
, EP_Reduced
|EP_TokenOnly
) );
3359 ExprSetProperty(pExpr
, EP_Subrtn
);
3360 pExpr
->y
.sub
.regReturn
= ++pParse
->nMem
;
3361 pExpr
->y
.sub
.iAddr
=
3362 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pExpr
->y
.sub
.regReturn
) + 1;
3364 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3365 ** is encountered if any of the following is true:
3367 ** * The right-hand side is a correlated subquery
3368 ** * The right-hand side is an expression list containing variables
3369 ** * We are inside a trigger
3371 ** If all of the above are false, then we can run this code just once
3372 ** save the results, and reuse the same result on subsequent invocations.
3374 if( !ExprHasProperty(pExpr
, EP_VarSelect
) ){
3375 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3378 /* For a SELECT, generate code to put the values for all columns of
3379 ** the first row into an array of registers and return the index of
3380 ** the first register.
3382 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3383 ** into a register and return that register number.
3385 ** In both cases, the query is augmented with "LIMIT 1". Any
3386 ** preexisting limit is discarded in place of the new LIMIT 1.
3388 ExplainQueryPlan2(addrExplain
, (pParse
, 1, "%sSCALAR SUBQUERY %d",
3389 addrOnce
?"":"CORRELATED ", pSel
->selId
));
3390 sqlite3VdbeScanStatusCounters(v
, addrExplain
, addrExplain
, -1);
3391 nReg
= pExpr
->op
==TK_SELECT
? pSel
->pEList
->nExpr
: 1;
3392 sqlite3SelectDestInit(&dest
, 0, pParse
->nMem
+1);
3393 pParse
->nMem
+= nReg
;
3394 if( pExpr
->op
==TK_SELECT
){
3395 dest
.eDest
= SRT_Mem
;
3396 dest
.iSdst
= dest
.iSDParm
;
3398 sqlite3VdbeAddOp3(v
, OP_Null
, 0, dest
.iSDParm
, dest
.iSDParm
+nReg
-1);
3399 VdbeComment((v
, "Init subquery result"));
3401 dest
.eDest
= SRT_Exists
;
3402 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
.iSDParm
);
3403 VdbeComment((v
, "Init EXISTS result"));
3406 /* The subquery already has a limit. If the pre-existing limit is X
3407 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3408 sqlite3
*db
= pParse
->db
;
3409 pLimit
= sqlite3Expr(db
, TK_INTEGER
, "0");
3411 pLimit
->affExpr
= SQLITE_AFF_NUMERIC
;
3412 pLimit
= sqlite3PExpr(pParse
, TK_NE
,
3413 sqlite3ExprDup(db
, pSel
->pLimit
->pLeft
, 0), pLimit
);
3415 sqlite3ExprDeferredDelete(pParse
, pSel
->pLimit
->pLeft
);
3416 pSel
->pLimit
->pLeft
= pLimit
;
3418 /* If there is no pre-existing limit add a limit of 1 */
3419 pLimit
= sqlite3Expr(pParse
->db
, TK_INTEGER
, "1");
3420 pSel
->pLimit
= sqlite3PExpr(pParse
, TK_LIMIT
, pLimit
, 0);
3423 if( sqlite3Select(pParse
, pSel
, &dest
) ){
3424 pExpr
->op2
= pExpr
->op
;
3425 pExpr
->op
= TK_ERROR
;
3428 pExpr
->iTable
= rReg
= dest
.iSDParm
;
3429 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
3431 sqlite3VdbeJumpHere(v
, addrOnce
);
3433 sqlite3VdbeScanStatusRange(v
, addrExplain
, addrExplain
, -1);
3435 /* Subroutine return */
3436 assert( ExprUseYSub(pExpr
) );
3437 assert( sqlite3VdbeGetOp(v
,pExpr
->y
.sub
.iAddr
-1)->opcode
==OP_BeginSubrtn
3439 sqlite3VdbeAddOp3(v
, OP_Return
, pExpr
->y
.sub
.regReturn
,
3440 pExpr
->y
.sub
.iAddr
, 1);
3442 sqlite3ClearTempRegCache(pParse
);
3445 #endif /* SQLITE_OMIT_SUBQUERY */
3447 #ifndef SQLITE_OMIT_SUBQUERY
3449 ** Expr pIn is an IN(...) expression. This function checks that the
3450 ** sub-select on the RHS of the IN() operator has the same number of
3451 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3452 ** a sub-query, that the LHS is a vector of size 1.
3454 int sqlite3ExprCheckIN(Parse
*pParse
, Expr
*pIn
){
3455 int nVector
= sqlite3ExprVectorSize(pIn
->pLeft
);
3456 if( ExprUseXSelect(pIn
) && !pParse
->db
->mallocFailed
){
3457 if( nVector
!=pIn
->x
.pSelect
->pEList
->nExpr
){
3458 sqlite3SubselectError(pParse
, pIn
->x
.pSelect
->pEList
->nExpr
, nVector
);
3461 }else if( nVector
!=1 ){
3462 sqlite3VectorErrorMsg(pParse
, pIn
->pLeft
);
3469 #ifndef SQLITE_OMIT_SUBQUERY
3471 ** Generate code for an IN expression.
3473 ** x IN (SELECT ...)
3474 ** x IN (value, value, ...)
3476 ** The left-hand side (LHS) is a scalar or vector expression. The
3477 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3478 ** subquery. If the RHS is a subquery, the number of result columns must
3479 ** match the number of columns in the vector on the LHS. If the RHS is
3480 ** a list of values, the LHS must be a scalar.
3482 ** The IN operator is true if the LHS value is contained within the RHS.
3483 ** The result is false if the LHS is definitely not in the RHS. The
3484 ** result is NULL if the presence of the LHS in the RHS cannot be
3485 ** determined due to NULLs.
3487 ** This routine generates code that jumps to destIfFalse if the LHS is not
3488 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3489 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3490 ** within the RHS then fall through.
3492 ** See the separate in-operator.md documentation file in the canonical
3493 ** SQLite source tree for additional information.
3495 static void sqlite3ExprCodeIN(
3496 Parse
*pParse
, /* Parsing and code generating context */
3497 Expr
*pExpr
, /* The IN expression */
3498 int destIfFalse
, /* Jump here if LHS is not contained in the RHS */
3499 int destIfNull
/* Jump here if the results are unknown due to NULLs */
3501 int rRhsHasNull
= 0; /* Register that is true if RHS contains NULL values */
3502 int eType
; /* Type of the RHS */
3503 int rLhs
; /* Register(s) holding the LHS values */
3504 int rLhsOrig
; /* LHS values prior to reordering by aiMap[] */
3505 Vdbe
*v
; /* Statement under construction */
3506 int *aiMap
= 0; /* Map from vector field to index column */
3507 char *zAff
= 0; /* Affinity string for comparisons */
3508 int nVector
; /* Size of vectors for this IN operator */
3509 int iDummy
; /* Dummy parameter to exprCodeVector() */
3510 Expr
*pLeft
; /* The LHS of the IN operator */
3511 int i
; /* loop counter */
3512 int destStep2
; /* Where to jump when NULLs seen in step 2 */
3513 int destStep6
= 0; /* Start of code for Step 6 */
3514 int addrTruthOp
; /* Address of opcode that determines the IN is true */
3515 int destNotNull
; /* Jump here if a comparison is not true in step 6 */
3516 int addrTop
; /* Top of the step-6 loop */
3517 int iTab
= 0; /* Index to use */
3518 u8 okConstFactor
= pParse
->okConstFactor
;
3520 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
3521 pLeft
= pExpr
->pLeft
;
3522 if( sqlite3ExprCheckIN(pParse
, pExpr
) ) return;
3523 zAff
= exprINAffinity(pParse
, pExpr
);
3524 nVector
= sqlite3ExprVectorSize(pExpr
->pLeft
);
3525 aiMap
= (int*)sqlite3DbMallocZero(
3526 pParse
->db
, nVector
*(sizeof(int) + sizeof(char)) + 1
3528 if( pParse
->db
->mallocFailed
) goto sqlite3ExprCodeIN_oom_error
;
3530 /* Attempt to compute the RHS. After this step, if anything other than
3531 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3532 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3533 ** the RHS has not yet been coded. */
3535 assert( v
!=0 ); /* OOM detected prior to this routine */
3536 VdbeNoopComment((v
, "begin IN expr"));
3537 eType
= sqlite3FindInIndex(pParse
, pExpr
,
3538 IN_INDEX_MEMBERSHIP
| IN_INDEX_NOOP_OK
,
3539 destIfFalse
==destIfNull
? 0 : &rRhsHasNull
,
3542 assert( pParse
->nErr
|| nVector
==1 || eType
==IN_INDEX_EPH
3543 || eType
==IN_INDEX_INDEX_ASC
|| eType
==IN_INDEX_INDEX_DESC
3546 /* Confirm that aiMap[] contains nVector integer values between 0 and
3548 for(i
=0; i
<nVector
; i
++){
3550 for(cnt
=j
=0; j
<nVector
; j
++) if( aiMap
[j
]==i
) cnt
++;
3555 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3556 ** vector, then it is stored in an array of nVector registers starting
3559 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3560 ** so that the fields are in the same order as an existing index. The
3561 ** aiMap[] array contains a mapping from the original LHS field order to
3562 ** the field order that matches the RHS index.
3564 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3565 ** even if it is constant, as OP_Affinity may be used on the register
3566 ** by code generated below. */
3567 assert( pParse
->okConstFactor
==okConstFactor
);
3568 pParse
->okConstFactor
= 0;
3569 rLhsOrig
= exprCodeVector(pParse
, pLeft
, &iDummy
);
3570 pParse
->okConstFactor
= okConstFactor
;
3571 for(i
=0; i
<nVector
&& aiMap
[i
]==i
; i
++){} /* Are LHS fields reordered? */
3573 /* LHS fields are not reordered */
3576 /* Need to reorder the LHS fields according to aiMap */
3577 rLhs
= sqlite3GetTempRange(pParse
, nVector
);
3578 for(i
=0; i
<nVector
; i
++){
3579 sqlite3VdbeAddOp3(v
, OP_Copy
, rLhsOrig
+i
, rLhs
+aiMap
[i
], 0);
3583 /* If sqlite3FindInIndex() did not find or create an index that is
3584 ** suitable for evaluating the IN operator, then evaluate using a
3585 ** sequence of comparisons.
3587 ** This is step (1) in the in-operator.md optimized algorithm.
3589 if( eType
==IN_INDEX_NOOP
){
3592 int labelOk
= sqlite3VdbeMakeLabel(pParse
);
3596 assert( ExprUseXList(pExpr
) );
3597 pList
= pExpr
->x
.pList
;
3598 pColl
= sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
3599 if( destIfNull
!=destIfFalse
){
3600 regCkNull
= sqlite3GetTempReg(pParse
);
3601 sqlite3VdbeAddOp3(v
, OP_BitAnd
, rLhs
, rLhs
, regCkNull
);
3603 for(ii
=0; ii
<pList
->nExpr
; ii
++){
3604 r2
= sqlite3ExprCodeTemp(pParse
, pList
->a
[ii
].pExpr
, ®ToFree
);
3605 if( regCkNull
&& sqlite3ExprCanBeNull(pList
->a
[ii
].pExpr
) ){
3606 sqlite3VdbeAddOp3(v
, OP_BitAnd
, regCkNull
, r2
, regCkNull
);
3608 sqlite3ReleaseTempReg(pParse
, regToFree
);
3609 if( ii
<pList
->nExpr
-1 || destIfNull
!=destIfFalse
){
3610 int op
= rLhs
!=r2
? OP_Eq
: OP_NotNull
;
3611 sqlite3VdbeAddOp4(v
, op
, rLhs
, labelOk
, r2
,
3612 (void*)pColl
, P4_COLLSEQ
);
3613 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1 && op
==OP_Eq
);
3614 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1 && op
==OP_Eq
);
3615 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1 && op
==OP_NotNull
);
3616 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1 && op
==OP_NotNull
);
3617 sqlite3VdbeChangeP5(v
, zAff
[0]);
3619 int op
= rLhs
!=r2
? OP_Ne
: OP_IsNull
;
3620 assert( destIfNull
==destIfFalse
);
3621 sqlite3VdbeAddOp4(v
, op
, rLhs
, destIfFalse
, r2
,
3622 (void*)pColl
, P4_COLLSEQ
);
3623 VdbeCoverageIf(v
, op
==OP_Ne
);
3624 VdbeCoverageIf(v
, op
==OP_IsNull
);
3625 sqlite3VdbeChangeP5(v
, zAff
[0] | SQLITE_JUMPIFNULL
);
3629 sqlite3VdbeAddOp2(v
, OP_IsNull
, regCkNull
, destIfNull
); VdbeCoverage(v
);
3630 sqlite3VdbeGoto(v
, destIfFalse
);
3632 sqlite3VdbeResolveLabel(v
, labelOk
);
3633 sqlite3ReleaseTempReg(pParse
, regCkNull
);
3634 goto sqlite3ExprCodeIN_finished
;
3637 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3638 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3639 ** We will then skip the binary search of the RHS.
3641 if( destIfNull
==destIfFalse
){
3642 destStep2
= destIfFalse
;
3644 destStep2
= destStep6
= sqlite3VdbeMakeLabel(pParse
);
3646 for(i
=0; i
<nVector
; i
++){
3647 Expr
*p
= sqlite3VectorFieldSubexpr(pExpr
->pLeft
, i
);
3648 if( pParse
->nErr
) goto sqlite3ExprCodeIN_oom_error
;
3649 if( sqlite3ExprCanBeNull(p
) ){
3650 sqlite3VdbeAddOp2(v
, OP_IsNull
, rLhs
+i
, destStep2
);
3655 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3656 ** of the RHS using the LHS as a probe. If found, the result is
3659 if( eType
==IN_INDEX_ROWID
){
3660 /* In this case, the RHS is the ROWID of table b-tree and so we also
3661 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3662 ** into a single opcode. */
3663 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, iTab
, destIfFalse
, rLhs
);
3665 addrTruthOp
= sqlite3VdbeAddOp0(v
, OP_Goto
); /* Return True */
3667 sqlite3VdbeAddOp4(v
, OP_Affinity
, rLhs
, nVector
, 0, zAff
, nVector
);
3668 if( destIfFalse
==destIfNull
){
3669 /* Combine Step 3 and Step 5 into a single opcode */
3670 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, iTab
, destIfFalse
,
3671 rLhs
, nVector
); VdbeCoverage(v
);
3672 goto sqlite3ExprCodeIN_finished
;
3674 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3675 addrTruthOp
= sqlite3VdbeAddOp4Int(v
, OP_Found
, iTab
, 0,
3676 rLhs
, nVector
); VdbeCoverage(v
);
3679 /* Step 4. If the RHS is known to be non-NULL and we did not find
3680 ** an match on the search above, then the result must be FALSE.
3682 if( rRhsHasNull
&& nVector
==1 ){
3683 sqlite3VdbeAddOp2(v
, OP_NotNull
, rRhsHasNull
, destIfFalse
);
3687 /* Step 5. If we do not care about the difference between NULL and
3688 ** FALSE, then just return false.
3690 if( destIfFalse
==destIfNull
) sqlite3VdbeGoto(v
, destIfFalse
);
3692 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3693 ** If any comparison is NULL, then the result is NULL. If all
3694 ** comparisons are FALSE then the final result is FALSE.
3696 ** For a scalar LHS, it is sufficient to check just the first row
3699 if( destStep6
) sqlite3VdbeResolveLabel(v
, destStep6
);
3700 addrTop
= sqlite3VdbeAddOp2(v
, OP_Rewind
, iTab
, destIfFalse
);
3703 destNotNull
= sqlite3VdbeMakeLabel(pParse
);
3705 /* For nVector==1, combine steps 6 and 7 by immediately returning
3706 ** FALSE if the first comparison is not NULL */
3707 destNotNull
= destIfFalse
;
3709 for(i
=0; i
<nVector
; i
++){
3712 int r3
= sqlite3GetTempReg(pParse
);
3713 p
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3714 pColl
= sqlite3ExprCollSeq(pParse
, p
);
3715 sqlite3VdbeAddOp3(v
, OP_Column
, iTab
, i
, r3
);
3716 sqlite3VdbeAddOp4(v
, OP_Ne
, rLhs
+i
, destNotNull
, r3
,
3717 (void*)pColl
, P4_COLLSEQ
);
3719 sqlite3ReleaseTempReg(pParse
, r3
);
3721 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfNull
);
3723 sqlite3VdbeResolveLabel(v
, destNotNull
);
3724 sqlite3VdbeAddOp2(v
, OP_Next
, iTab
, addrTop
+1);
3727 /* Step 7: If we reach this point, we know that the result must
3729 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfFalse
);
3732 /* Jumps here in order to return true. */
3733 sqlite3VdbeJumpHere(v
, addrTruthOp
);
3735 sqlite3ExprCodeIN_finished
:
3736 if( rLhs
!=rLhsOrig
) sqlite3ReleaseTempReg(pParse
, rLhs
);
3737 VdbeComment((v
, "end IN expr"));
3738 sqlite3ExprCodeIN_oom_error
:
3739 sqlite3DbFree(pParse
->db
, aiMap
);
3740 sqlite3DbFree(pParse
->db
, zAff
);
3742 #endif /* SQLITE_OMIT_SUBQUERY */
3744 #ifndef SQLITE_OMIT_FLOATING_POINT
3746 ** Generate an instruction that will put the floating point
3747 ** value described by z[0..n-1] into register iMem.
3749 ** The z[] string will probably not be zero-terminated. But the
3750 ** z[n] character is guaranteed to be something that does not look
3751 ** like the continuation of the number.
3753 static void codeReal(Vdbe
*v
, const char *z
, int negateFlag
, int iMem
){
3756 sqlite3AtoF(z
, &value
, sqlite3Strlen30(z
), SQLITE_UTF8
);
3757 assert( !sqlite3IsNaN(value
) ); /* The new AtoF never returns NaN */
3758 if( negateFlag
) value
= -value
;
3759 sqlite3VdbeAddOp4Dup8(v
, OP_Real
, 0, iMem
, 0, (u8
*)&value
, P4_REAL
);
3766 ** Generate an instruction that will put the integer describe by
3767 ** text z[0..n-1] into register iMem.
3769 ** Expr.u.zToken is always UTF8 and zero-terminated.
3771 static void codeInteger(Parse
*pParse
, Expr
*pExpr
, int negFlag
, int iMem
){
3772 Vdbe
*v
= pParse
->pVdbe
;
3773 if( pExpr
->flags
& EP_IntValue
){
3774 int i
= pExpr
->u
.iValue
;
3776 if( negFlag
) i
= -i
;
3777 sqlite3VdbeAddOp2(v
, OP_Integer
, i
, iMem
);
3781 const char *z
= pExpr
->u
.zToken
;
3783 c
= sqlite3DecOrHexToI64(z
, &value
);
3784 if( (c
==3 && !negFlag
) || (c
==2) || (negFlag
&& value
==SMALLEST_INT64
)){
3785 #ifdef SQLITE_OMIT_FLOATING_POINT
3786 sqlite3ErrorMsg(pParse
, "oversized integer: %s%#T", negFlag
?"-":"",pExpr
);
3788 #ifndef SQLITE_OMIT_HEX_INTEGER
3789 if( sqlite3_strnicmp(z
,"0x",2)==0 ){
3790 sqlite3ErrorMsg(pParse
, "hex literal too big: %s%#T",
3791 negFlag
?"-":"",pExpr
);
3795 codeReal(v
, z
, negFlag
, iMem
);
3799 if( negFlag
){ value
= c
==3 ? SMALLEST_INT64
: -value
; }
3800 sqlite3VdbeAddOp4Dup8(v
, OP_Int64
, 0, iMem
, 0, (u8
*)&value
, P4_INT64
);
3806 /* Generate code that will load into register regOut a value that is
3807 ** appropriate for the iIdxCol-th column of index pIdx.
3809 void sqlite3ExprCodeLoadIndexColumn(
3810 Parse
*pParse
, /* The parsing context */
3811 Index
*pIdx
, /* The index whose column is to be loaded */
3812 int iTabCur
, /* Cursor pointing to a table row */
3813 int iIdxCol
, /* The column of the index to be loaded */
3814 int regOut
/* Store the index column value in this register */
3816 i16 iTabCol
= pIdx
->aiColumn
[iIdxCol
];
3817 if( iTabCol
==XN_EXPR
){
3818 assert( pIdx
->aColExpr
);
3819 assert( pIdx
->aColExpr
->nExpr
>iIdxCol
);
3820 pParse
->iSelfTab
= iTabCur
+ 1;
3821 sqlite3ExprCodeCopy(pParse
, pIdx
->aColExpr
->a
[iIdxCol
].pExpr
, regOut
);
3822 pParse
->iSelfTab
= 0;
3824 sqlite3ExprCodeGetColumnOfTable(pParse
->pVdbe
, pIdx
->pTable
, iTabCur
,
3829 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3831 ** Generate code that will compute the value of generated column pCol
3832 ** and store the result in register regOut
3834 void sqlite3ExprCodeGeneratedColumn(
3835 Parse
*pParse
, /* Parsing context */
3836 Table
*pTab
, /* Table containing the generated column */
3837 Column
*pCol
, /* The generated column */
3838 int regOut
/* Put the result in this register */
3841 Vdbe
*v
= pParse
->pVdbe
;
3843 assert( pParse
->iSelfTab
!=0 );
3844 if( pParse
->iSelfTab
>0 ){
3845 iAddr
= sqlite3VdbeAddOp3(v
, OP_IfNullRow
, pParse
->iSelfTab
-1, 0, regOut
);
3849 sqlite3ExprCodeCopy(pParse
, sqlite3ColumnExpr(pTab
,pCol
), regOut
);
3850 if( pCol
->affinity
>=SQLITE_AFF_TEXT
){
3851 sqlite3VdbeAddOp4(v
, OP_Affinity
, regOut
, 1, 0, &pCol
->affinity
, 1);
3853 if( iAddr
) sqlite3VdbeJumpHere(v
, iAddr
);
3855 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
3858 ** Generate code to extract the value of the iCol-th column of a table.
3860 void sqlite3ExprCodeGetColumnOfTable(
3861 Vdbe
*v
, /* Parsing context */
3862 Table
*pTab
, /* The table containing the value */
3863 int iTabCur
, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
3864 int iCol
, /* Index of the column to extract */
3865 int regOut
/* Extract the value into this register */
3870 if( iCol
<0 || iCol
==pTab
->iPKey
){
3871 sqlite3VdbeAddOp2(v
, OP_Rowid
, iTabCur
, regOut
);
3872 VdbeComment((v
, "%s.rowid", pTab
->zName
));
3876 if( IsVirtual(pTab
) ){
3879 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3880 }else if( (pCol
= &pTab
->aCol
[iCol
])->colFlags
& COLFLAG_VIRTUAL
){
3881 Parse
*pParse
= sqlite3VdbeParser(v
);
3882 if( pCol
->colFlags
& COLFLAG_BUSY
){
3883 sqlite3ErrorMsg(pParse
, "generated column loop on \"%s\"",
3886 int savedSelfTab
= pParse
->iSelfTab
;
3887 pCol
->colFlags
|= COLFLAG_BUSY
;
3888 pParse
->iSelfTab
= iTabCur
+1;
3889 sqlite3ExprCodeGeneratedColumn(pParse
, pTab
, pCol
, regOut
);
3890 pParse
->iSelfTab
= savedSelfTab
;
3891 pCol
->colFlags
&= ~COLFLAG_BUSY
;
3895 }else if( !HasRowid(pTab
) ){
3896 testcase( iCol
!=sqlite3TableColumnToStorage(pTab
, iCol
) );
3897 x
= sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab
), iCol
);
3900 x
= sqlite3TableColumnToStorage(pTab
,iCol
);
3901 testcase( x
!=iCol
);
3904 sqlite3VdbeAddOp3(v
, op
, iTabCur
, x
, regOut
);
3905 sqlite3ColumnDefault(v
, pTab
, iCol
, regOut
);
3910 ** Generate code that will extract the iColumn-th column from
3911 ** table pTab and store the column value in register iReg.
3913 ** There must be an open cursor to pTab in iTable when this routine
3914 ** is called. If iColumn<0 then code is generated that extracts the rowid.
3916 int sqlite3ExprCodeGetColumn(
3917 Parse
*pParse
, /* Parsing and code generating context */
3918 Table
*pTab
, /* Description of the table we are reading from */
3919 int iColumn
, /* Index of the table column */
3920 int iTable
, /* The cursor pointing to the table */
3921 int iReg
, /* Store results here */
3922 u8 p5
/* P5 value for OP_Column + FLAGS */
3924 assert( pParse
->pVdbe
!=0 );
3925 sqlite3ExprCodeGetColumnOfTable(pParse
->pVdbe
, pTab
, iTable
, iColumn
, iReg
);
3927 VdbeOp
*pOp
= sqlite3VdbeGetLastOp(pParse
->pVdbe
);
3928 if( pOp
->opcode
==OP_Column
) pOp
->p5
= p5
;
3934 ** Generate code to move content from registers iFrom...iFrom+nReg-1
3935 ** over to iTo..iTo+nReg-1.
3937 void sqlite3ExprCodeMove(Parse
*pParse
, int iFrom
, int iTo
, int nReg
){
3938 sqlite3VdbeAddOp3(pParse
->pVdbe
, OP_Move
, iFrom
, iTo
, nReg
);
3942 ** Convert a scalar expression node to a TK_REGISTER referencing
3943 ** register iReg. The caller must ensure that iReg already contains
3944 ** the correct value for the expression.
3946 static void exprToRegister(Expr
*pExpr
, int iReg
){
3947 Expr
*p
= sqlite3ExprSkipCollateAndLikely(pExpr
);
3948 if( NEVER(p
==0) ) return;
3950 p
->op
= TK_REGISTER
;
3952 ExprClearProperty(p
, EP_Skip
);
3956 ** Evaluate an expression (either a vector or a scalar expression) and store
3957 ** the result in continguous temporary registers. Return the index of
3958 ** the first register used to store the result.
3960 ** If the returned result register is a temporary scalar, then also write
3961 ** that register number into *piFreeable. If the returned result register
3962 ** is not a temporary or if the expression is a vector set *piFreeable
3965 static int exprCodeVector(Parse
*pParse
, Expr
*p
, int *piFreeable
){
3967 int nResult
= sqlite3ExprVectorSize(p
);
3969 iResult
= sqlite3ExprCodeTemp(pParse
, p
, piFreeable
);
3972 if( p
->op
==TK_SELECT
){
3973 #if SQLITE_OMIT_SUBQUERY
3976 iResult
= sqlite3CodeSubselect(pParse
, p
);
3980 iResult
= pParse
->nMem
+1;
3981 pParse
->nMem
+= nResult
;
3982 assert( ExprUseXList(p
) );
3983 for(i
=0; i
<nResult
; i
++){
3984 sqlite3ExprCodeFactorable(pParse
, p
->x
.pList
->a
[i
].pExpr
, i
+iResult
);
3992 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
3993 ** so that a subsequent copy will not be merged into this one.
3995 static void setDoNotMergeFlagOnCopy(Vdbe
*v
){
3996 if( sqlite3VdbeGetLastOp(v
)->opcode
==OP_Copy
){
3997 sqlite3VdbeChangeP5(v
, 1); /* Tag trailing OP_Copy as not mergable */
4002 ** Generate code to implement special SQL functions that are implemented
4003 ** in-line rather than by using the usual callbacks.
4005 static int exprCodeInlineFunction(
4006 Parse
*pParse
, /* Parsing context */
4007 ExprList
*pFarg
, /* List of function arguments */
4008 int iFuncId
, /* Function ID. One of the INTFUNC_... values */
4009 int target
/* Store function result in this register */
4012 Vdbe
*v
= pParse
->pVdbe
;
4015 nFarg
= pFarg
->nExpr
;
4016 assert( nFarg
>0 ); /* All in-line functions have at least one argument */
4018 case INLINEFUNC_coalesce
: {
4019 /* Attempt a direct implementation of the built-in COALESCE() and
4020 ** IFNULL() functions. This avoids unnecessary evaluation of
4021 ** arguments past the first non-NULL argument.
4023 int endCoalesce
= sqlite3VdbeMakeLabel(pParse
);
4026 sqlite3ExprCode(pParse
, pFarg
->a
[0].pExpr
, target
);
4027 for(i
=1; i
<nFarg
; i
++){
4028 sqlite3VdbeAddOp2(v
, OP_NotNull
, target
, endCoalesce
);
4030 sqlite3ExprCode(pParse
, pFarg
->a
[i
].pExpr
, target
);
4032 setDoNotMergeFlagOnCopy(v
);
4033 sqlite3VdbeResolveLabel(v
, endCoalesce
);
4036 case INLINEFUNC_iif
: {
4038 memset(&caseExpr
, 0, sizeof(caseExpr
));
4039 caseExpr
.op
= TK_CASE
;
4040 caseExpr
.x
.pList
= pFarg
;
4041 return sqlite3ExprCodeTarget(pParse
, &caseExpr
, target
);
4043 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4044 case INLINEFUNC_sqlite_offset
: {
4045 Expr
*pArg
= pFarg
->a
[0].pExpr
;
4046 if( pArg
->op
==TK_COLUMN
&& pArg
->iTable
>=0 ){
4047 sqlite3VdbeAddOp3(v
, OP_Offset
, pArg
->iTable
, pArg
->iColumn
, target
);
4049 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4055 /* The UNLIKELY() function is a no-op. The result is the value
4056 ** of the first argument.
4058 assert( nFarg
==1 || nFarg
==2 );
4059 target
= sqlite3ExprCodeTarget(pParse
, pFarg
->a
[0].pExpr
, target
);
4063 /***********************************************************************
4064 ** Test-only SQL functions that are only usable if enabled
4065 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4067 #if !defined(SQLITE_UNTESTABLE)
4068 case INLINEFUNC_expr_compare
: {
4069 /* Compare two expressions using sqlite3ExprCompare() */
4071 sqlite3VdbeAddOp2(v
, OP_Integer
,
4072 sqlite3ExprCompare(0,pFarg
->a
[0].pExpr
, pFarg
->a
[1].pExpr
,-1),
4077 case INLINEFUNC_expr_implies_expr
: {
4078 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4080 sqlite3VdbeAddOp2(v
, OP_Integer
,
4081 sqlite3ExprImpliesExpr(pParse
,pFarg
->a
[0].pExpr
, pFarg
->a
[1].pExpr
,-1),
4086 case INLINEFUNC_implies_nonnull_row
: {
4087 /* REsult of sqlite3ExprImpliesNonNullRow() */
4090 pA1
= pFarg
->a
[1].pExpr
;
4091 if( pA1
->op
==TK_COLUMN
){
4092 sqlite3VdbeAddOp2(v
, OP_Integer
,
4093 sqlite3ExprImpliesNonNullRow(pFarg
->a
[0].pExpr
,pA1
->iTable
),
4096 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4101 case INLINEFUNC_affinity
: {
4102 /* The AFFINITY() function evaluates to a string that describes
4103 ** the type affinity of the argument. This is used for testing of
4104 ** the SQLite type logic.
4106 const char *azAff
[] = { "blob", "text", "numeric", "integer",
4107 "real", "flexnum" };
4110 aff
= sqlite3ExprAffinity(pFarg
->a
[0].pExpr
);
4111 assert( aff
<=SQLITE_AFF_NONE
4112 || (aff
>=SQLITE_AFF_BLOB
&& aff
<=SQLITE_AFF_FLEXNUM
) );
4113 sqlite3VdbeLoadString(v
, target
,
4114 (aff
<=SQLITE_AFF_NONE
) ? "none" : azAff
[aff
-SQLITE_AFF_BLOB
]);
4117 #endif /* !defined(SQLITE_UNTESTABLE) */
4123 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4124 ** If it is, then resolve the expression by reading from the index and
4125 ** return the register into which the value has been read. If pExpr is
4126 ** not an indexed expression, then return negative.
4128 static SQLITE_NOINLINE
int sqlite3IndexedExprLookup(
4129 Parse
*pParse
, /* The parsing context */
4130 Expr
*pExpr
, /* The expression to potentially bypass */
4131 int target
/* Where to store the result of the expression */
4135 for(p
=pParse
->pIdxEpr
; p
; p
=p
->pIENext
){
4137 int iDataCur
= p
->iDataCur
;
4138 if( iDataCur
<0 ) continue;
4139 if( pParse
->iSelfTab
){
4140 if( p
->iDataCur
!=pParse
->iSelfTab
-1 ) continue;
4143 if( sqlite3ExprCompare(0, pExpr
, p
->pExpr
, iDataCur
)!=0 ) continue;
4144 assert( p
->aff
>=SQLITE_AFF_BLOB
&& p
->aff
<=SQLITE_AFF_NUMERIC
);
4145 exprAff
= sqlite3ExprAffinity(pExpr
);
4146 if( (exprAff
<=SQLITE_AFF_BLOB
&& p
->aff
!=SQLITE_AFF_BLOB
)
4147 || (exprAff
==SQLITE_AFF_TEXT
&& p
->aff
!=SQLITE_AFF_TEXT
)
4148 || (exprAff
>=SQLITE_AFF_NUMERIC
&& p
->aff
!=SQLITE_AFF_NUMERIC
)
4150 /* Affinity mismatch on a generated column */
4156 if( p
->bMaybeNullRow
){
4157 /* If the index is on a NULL row due to an outer join, then we
4158 ** cannot extract the value from the index. The value must be
4159 ** computed using the original expression. */
4160 int addr
= sqlite3VdbeCurrentAddr(v
);
4161 sqlite3VdbeAddOp3(v
, OP_IfNullRow
, p
->iIdxCur
, addr
+3, target
);
4163 sqlite3VdbeAddOp3(v
, OP_Column
, p
->iIdxCur
, p
->iIdxCol
, target
);
4164 VdbeComment((v
, "%s expr-column %d", p
->zIdxName
, p
->iIdxCol
));
4165 sqlite3VdbeGoto(v
, 0);
4166 p
= pParse
->pIdxEpr
;
4167 pParse
->pIdxEpr
= 0;
4168 sqlite3ExprCode(pParse
, pExpr
, target
);
4169 pParse
->pIdxEpr
= p
;
4170 sqlite3VdbeJumpHere(v
, addr
+2);
4172 sqlite3VdbeAddOp3(v
, OP_Column
, p
->iIdxCur
, p
->iIdxCol
, target
);
4173 VdbeComment((v
, "%s expr-column %d", p
->zIdxName
, p
->iIdxCol
));
4177 return -1; /* Not found */
4182 ** Generate code into the current Vdbe to evaluate the given
4183 ** expression. Attempt to store the results in register "target".
4184 ** Return the register where results are stored.
4186 ** With this routine, there is no guarantee that results will
4187 ** be stored in target. The result might be stored in some other
4188 ** register if it is convenient to do so. The calling function
4189 ** must check the return code and move the results to the desired
4192 int sqlite3ExprCodeTarget(Parse
*pParse
, Expr
*pExpr
, int target
){
4193 Vdbe
*v
= pParse
->pVdbe
; /* The VM under construction */
4194 int op
; /* The opcode being coded */
4195 int inReg
= target
; /* Results stored in register inReg */
4196 int regFree1
= 0; /* If non-zero free this temporary register */
4197 int regFree2
= 0; /* If non-zero free this temporary register */
4198 int r1
, r2
; /* Various register numbers */
4199 Expr tempX
; /* Temporary expression node */
4202 assert( target
>0 && target
<=pParse
->nMem
);
4208 }else if( pParse
->pIdxEpr
!=0
4209 && !ExprHasProperty(pExpr
, EP_Leaf
)
4210 && (r1
= sqlite3IndexedExprLookup(pParse
, pExpr
, target
))>=0
4214 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
4218 case TK_AGG_COLUMN
: {
4219 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
4220 struct AggInfo_col
*pCol
;
4221 assert( pAggInfo
!=0 );
4222 assert( pExpr
->iAgg
>=0 && pExpr
->iAgg
<pAggInfo
->nColumn
);
4223 pCol
= &pAggInfo
->aCol
[pExpr
->iAgg
];
4224 if( !pAggInfo
->directMode
){
4225 return AggInfoColumnReg(pAggInfo
, pExpr
->iAgg
);
4226 }else if( pAggInfo
->useSortingIdx
){
4227 Table
*pTab
= pCol
->pTab
;
4228 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
4229 pCol
->iSorterColumn
, target
);
4231 /* No comment added */
4232 }else if( pCol
->iColumn
<0 ){
4233 VdbeComment((v
,"%s.rowid",pTab
->zName
));
4235 VdbeComment((v
,"%s.%s",
4236 pTab
->zName
, pTab
->aCol
[pCol
->iColumn
].zCnName
));
4237 if( pTab
->aCol
[pCol
->iColumn
].affinity
==SQLITE_AFF_REAL
){
4238 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4242 }else if( pExpr
->y
.pTab
==0 ){
4243 /* This case happens when the argument to an aggregate function
4244 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4245 sqlite3VdbeAddOp3(v
, OP_Column
, pExpr
->iTable
, pExpr
->iColumn
, target
);
4248 /* Otherwise, fall thru into the TK_COLUMN case */
4249 /* no break */ deliberate_fall_through
4252 int iTab
= pExpr
->iTable
;
4254 if( ExprHasProperty(pExpr
, EP_FixedCol
) ){
4255 /* This COLUMN expression is really a constant due to WHERE clause
4256 ** constraints, and that constant is coded by the pExpr->pLeft
4257 ** expresssion. However, make sure the constant has the correct
4258 ** datatype by applying the Affinity of the table column to the
4262 iReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
,target
);
4263 assert( ExprUseYTab(pExpr
) );
4264 assert( pExpr
->y
.pTab
!=0 );
4265 aff
= sqlite3TableColumnAffinity(pExpr
->y
.pTab
, pExpr
->iColumn
);
4266 if( aff
>SQLITE_AFF_BLOB
){
4267 static const char zAff
[] = "B\000C\000D\000E\000F";
4268 assert( SQLITE_AFF_BLOB
=='A' );
4269 assert( SQLITE_AFF_TEXT
=='B' );
4270 sqlite3VdbeAddOp4(v
, OP_Affinity
, iReg
, 1, 0,
4271 &zAff
[(aff
-'B')*2], P4_STATIC
);
4276 if( pParse
->iSelfTab
<0 ){
4277 /* Other columns in the same row for CHECK constraints or
4278 ** generated columns or for inserting into partial index.
4279 ** The row is unpacked into registers beginning at
4280 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4281 ** immediately prior to the first column.
4286 int iCol
= pExpr
->iColumn
;
4287 assert( ExprUseYTab(pExpr
) );
4288 pTab
= pExpr
->y
.pTab
;
4290 assert( iCol
>=XN_ROWID
);
4291 assert( iCol
<pTab
->nCol
);
4293 return -1-pParse
->iSelfTab
;
4295 pCol
= pTab
->aCol
+ iCol
;
4296 testcase( iCol
!=sqlite3TableColumnToStorage(pTab
,iCol
) );
4297 iSrc
= sqlite3TableColumnToStorage(pTab
, iCol
) - pParse
->iSelfTab
;
4298 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4299 if( pCol
->colFlags
& COLFLAG_GENERATED
){
4300 if( pCol
->colFlags
& COLFLAG_BUSY
){
4301 sqlite3ErrorMsg(pParse
, "generated column loop on \"%s\"",
4305 pCol
->colFlags
|= COLFLAG_BUSY
;
4306 if( pCol
->colFlags
& COLFLAG_NOTAVAIL
){
4307 sqlite3ExprCodeGeneratedColumn(pParse
, pTab
, pCol
, iSrc
);
4309 pCol
->colFlags
&= ~(COLFLAG_BUSY
|COLFLAG_NOTAVAIL
);
4312 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4313 if( pCol
->affinity
==SQLITE_AFF_REAL
){
4314 sqlite3VdbeAddOp2(v
, OP_SCopy
, iSrc
, target
);
4315 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4321 /* Coding an expression that is part of an index where column names
4322 ** in the index refer to the table to which the index belongs */
4323 iTab
= pParse
->iSelfTab
- 1;
4326 assert( ExprUseYTab(pExpr
) );
4327 assert( pExpr
->y
.pTab
!=0 );
4328 iReg
= sqlite3ExprCodeGetColumn(pParse
, pExpr
->y
.pTab
,
4329 pExpr
->iColumn
, iTab
, target
,
4334 codeInteger(pParse
, pExpr
, 0, target
);
4337 case TK_TRUEFALSE
: {
4338 sqlite3VdbeAddOp2(v
, OP_Integer
, sqlite3ExprTruthValue(pExpr
), target
);
4341 #ifndef SQLITE_OMIT_FLOATING_POINT
4343 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4344 codeReal(v
, pExpr
->u
.zToken
, 0, target
);
4349 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4350 sqlite3VdbeLoadString(v
, target
, pExpr
->u
.zToken
);
4354 /* Make NULL the default case so that if a bug causes an illegal
4355 ** Expr node to be passed into this function, it will be handled
4356 ** sanely and not crash. But keep the assert() to bring the problem
4357 ** to the attention of the developers. */
4358 assert( op
==TK_NULL
|| op
==TK_ERROR
|| pParse
->db
->mallocFailed
);
4359 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4362 #ifndef SQLITE_OMIT_BLOB_LITERAL
4367 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4368 assert( pExpr
->u
.zToken
[0]=='x' || pExpr
->u
.zToken
[0]=='X' );
4369 assert( pExpr
->u
.zToken
[1]=='\'' );
4370 z
= &pExpr
->u
.zToken
[2];
4371 n
= sqlite3Strlen30(z
) - 1;
4372 assert( z
[n
]=='\'' );
4373 zBlob
= sqlite3HexToBlob(sqlite3VdbeDb(v
), z
, n
);
4374 sqlite3VdbeAddOp4(v
, OP_Blob
, n
/2, target
, 0, zBlob
, P4_DYNAMIC
);
4379 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4380 assert( pExpr
->u
.zToken
!=0 );
4381 assert( pExpr
->u
.zToken
[0]!=0 );
4382 sqlite3VdbeAddOp2(v
, OP_Variable
, pExpr
->iColumn
, target
);
4383 if( pExpr
->u
.zToken
[1]!=0 ){
4384 const char *z
= sqlite3VListNumToName(pParse
->pVList
, pExpr
->iColumn
);
4385 assert( pExpr
->u
.zToken
[0]=='?' || (z
&& !strcmp(pExpr
->u
.zToken
, z
)) );
4386 pParse
->pVList
[0] = 0; /* Indicate VList may no longer be enlarged */
4387 sqlite3VdbeAppendP4(v
, (char*)z
, P4_STATIC
);
4392 return pExpr
->iTable
;
4394 #ifndef SQLITE_OMIT_CAST
4396 /* Expressions of the form: CAST(pLeft AS token) */
4397 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
, target
);
4398 if( inReg
!=target
){
4399 sqlite3VdbeAddOp2(v
, OP_SCopy
, inReg
, target
);
4402 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4403 sqlite3VdbeAddOp2(v
, OP_Cast
, target
,
4404 sqlite3AffinityType(pExpr
->u
.zToken
, 0));
4407 #endif /* SQLITE_OMIT_CAST */
4410 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
4419 Expr
*pLeft
= pExpr
->pLeft
;
4420 if( sqlite3ExprIsVector(pLeft
) ){
4421 codeVectorCompare(pParse
, pExpr
, target
, op
, p5
);
4423 r1
= sqlite3ExprCodeTemp(pParse
, pLeft
, ®Free1
);
4424 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
4425 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, inReg
);
4426 codeCompare(pParse
, pLeft
, pExpr
->pRight
, op
, r1
, r2
,
4427 sqlite3VdbeCurrentAddr(v
)+2, p5
,
4428 ExprHasProperty(pExpr
,EP_Commuted
));
4429 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
4430 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
4431 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
4432 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
4433 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
4434 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
4435 if( p5
==SQLITE_NULLEQ
){
4436 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, inReg
);
4438 sqlite3VdbeAddOp3(v
, OP_ZeroOrNull
, r1
, inReg
, r2
);
4440 testcase( regFree1
==0 );
4441 testcase( regFree2
==0 );
4457 assert( TK_AND
==OP_And
); testcase( op
==TK_AND
);
4458 assert( TK_OR
==OP_Or
); testcase( op
==TK_OR
);
4459 assert( TK_PLUS
==OP_Add
); testcase( op
==TK_PLUS
);
4460 assert( TK_MINUS
==OP_Subtract
); testcase( op
==TK_MINUS
);
4461 assert( TK_REM
==OP_Remainder
); testcase( op
==TK_REM
);
4462 assert( TK_BITAND
==OP_BitAnd
); testcase( op
==TK_BITAND
);
4463 assert( TK_BITOR
==OP_BitOr
); testcase( op
==TK_BITOR
);
4464 assert( TK_SLASH
==OP_Divide
); testcase( op
==TK_SLASH
);
4465 assert( TK_LSHIFT
==OP_ShiftLeft
); testcase( op
==TK_LSHIFT
);
4466 assert( TK_RSHIFT
==OP_ShiftRight
); testcase( op
==TK_RSHIFT
);
4467 assert( TK_CONCAT
==OP_Concat
); testcase( op
==TK_CONCAT
);
4468 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4469 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
4470 sqlite3VdbeAddOp3(v
, op
, r2
, r1
, target
);
4471 testcase( regFree1
==0 );
4472 testcase( regFree2
==0 );
4476 Expr
*pLeft
= pExpr
->pLeft
;
4478 if( pLeft
->op
==TK_INTEGER
){
4479 codeInteger(pParse
, pLeft
, 1, target
);
4481 #ifndef SQLITE_OMIT_FLOATING_POINT
4482 }else if( pLeft
->op
==TK_FLOAT
){
4483 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4484 codeReal(v
, pLeft
->u
.zToken
, 1, target
);
4488 tempX
.op
= TK_INTEGER
;
4489 tempX
.flags
= EP_IntValue
|EP_TokenOnly
;
4491 ExprClearVVAProperties(&tempX
);
4492 r1
= sqlite3ExprCodeTemp(pParse
, &tempX
, ®Free1
);
4493 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free2
);
4494 sqlite3VdbeAddOp3(v
, OP_Subtract
, r2
, r1
, target
);
4495 testcase( regFree2
==0 );
4501 assert( TK_BITNOT
==OP_BitNot
); testcase( op
==TK_BITNOT
);
4502 assert( TK_NOT
==OP_Not
); testcase( op
==TK_NOT
);
4503 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4504 testcase( regFree1
==0 );
4505 sqlite3VdbeAddOp2(v
, op
, r1
, inReg
);
4509 int isTrue
; /* IS TRUE or IS NOT TRUE */
4510 int bNormal
; /* IS TRUE or IS FALSE */
4511 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4512 testcase( regFree1
==0 );
4513 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
4514 bNormal
= pExpr
->op2
==TK_IS
;
4515 testcase( isTrue
&& bNormal
);
4516 testcase( !isTrue
&& bNormal
);
4517 sqlite3VdbeAddOp4Int(v
, OP_IsTrue
, r1
, inReg
, !isTrue
, isTrue
^ bNormal
);
4523 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
4524 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
4525 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
4526 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4527 testcase( regFree1
==0 );
4528 addr
= sqlite3VdbeAddOp1(v
, op
, r1
);
4529 VdbeCoverageIf(v
, op
==TK_ISNULL
);
4530 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
4531 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, target
);
4532 sqlite3VdbeJumpHere(v
, addr
);
4535 case TK_AGG_FUNCTION
: {
4536 AggInfo
*pInfo
= pExpr
->pAggInfo
;
4538 || NEVER(pExpr
->iAgg
<0)
4539 || NEVER(pExpr
->iAgg
>=pInfo
->nFunc
)
4541 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4542 sqlite3ErrorMsg(pParse
, "misuse of aggregate: %#T()", pExpr
);
4544 return AggInfoFuncReg(pInfo
, pExpr
->iAgg
);
4549 ExprList
*pFarg
; /* List of function arguments */
4550 int nFarg
; /* Number of function arguments */
4551 FuncDef
*pDef
; /* The function definition object */
4552 const char *zId
; /* The function name */
4553 u32 constMask
= 0; /* Mask of function arguments that are constant */
4554 int i
; /* Loop counter */
4555 sqlite3
*db
= pParse
->db
; /* The database connection */
4556 u8 enc
= ENC(db
); /* The text encoding used by this database */
4557 CollSeq
*pColl
= 0; /* A collating sequence */
4559 #ifndef SQLITE_OMIT_WINDOWFUNC
4560 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
4561 return pExpr
->y
.pWin
->regResult
;
4565 if( ConstFactorOk(pParse
) && sqlite3ExprIsConstantNotJoin(pExpr
) ){
4566 /* SQL functions can be expensive. So try to avoid running them
4567 ** multiple times if we know they always give the same result */
4568 return sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, -1);
4570 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
) );
4571 assert( ExprUseXList(pExpr
) );
4572 pFarg
= pExpr
->x
.pList
;
4573 nFarg
= pFarg
? pFarg
->nExpr
: 0;
4574 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4575 zId
= pExpr
->u
.zToken
;
4576 pDef
= sqlite3FindFunction(db
, zId
, nFarg
, enc
, 0);
4577 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4578 if( pDef
==0 && pParse
->explain
){
4579 pDef
= sqlite3FindFunction(db
, "unknown", nFarg
, enc
, 0);
4582 if( pDef
==0 || pDef
->xFinalize
!=0 ){
4583 sqlite3ErrorMsg(pParse
, "unknown function: %#T()", pExpr
);
4586 if( pDef
->funcFlags
& SQLITE_FUNC_INLINE
){
4587 assert( (pDef
->funcFlags
& SQLITE_FUNC_UNSAFE
)==0 );
4588 assert( (pDef
->funcFlags
& SQLITE_FUNC_DIRECT
)==0 );
4589 return exprCodeInlineFunction(pParse
, pFarg
,
4590 SQLITE_PTR_TO_INT(pDef
->pUserData
), target
);
4591 }else if( pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
) ){
4592 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
4595 for(i
=0; i
<nFarg
; i
++){
4596 if( i
<32 && sqlite3ExprIsConstant(pFarg
->a
[i
].pExpr
) ){
4598 constMask
|= MASKBIT32(i
);
4600 if( (pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
)!=0 && !pColl
){
4601 pColl
= sqlite3ExprCollSeq(pParse
, pFarg
->a
[i
].pExpr
);
4606 r1
= pParse
->nMem
+1;
4607 pParse
->nMem
+= nFarg
;
4609 r1
= sqlite3GetTempRange(pParse
, nFarg
);
4612 /* For length() and typeof() functions with a column argument,
4613 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4614 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
4617 if( (pDef
->funcFlags
& (SQLITE_FUNC_LENGTH
|SQLITE_FUNC_TYPEOF
))!=0 ){
4620 assert( pFarg
->a
[0].pExpr
!=0 );
4621 exprOp
= pFarg
->a
[0].pExpr
->op
;
4622 if( exprOp
==TK_COLUMN
|| exprOp
==TK_AGG_COLUMN
){
4623 assert( SQLITE_FUNC_LENGTH
==OPFLAG_LENGTHARG
);
4624 assert( SQLITE_FUNC_TYPEOF
==OPFLAG_TYPEOFARG
);
4625 testcase( pDef
->funcFlags
& OPFLAG_LENGTHARG
);
4626 pFarg
->a
[0].pExpr
->op2
=
4627 pDef
->funcFlags
& (OPFLAG_LENGTHARG
|OPFLAG_TYPEOFARG
);
4631 sqlite3ExprCodeExprList(pParse
, pFarg
, r1
, 0,
4632 SQLITE_ECEL_DUP
|SQLITE_ECEL_FACTOR
);
4636 #ifndef SQLITE_OMIT_VIRTUALTABLE
4637 /* Possibly overload the function if the first argument is
4638 ** a virtual table column.
4640 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4641 ** second argument, not the first, as the argument to test to
4642 ** see if it is a column in a virtual table. This is done because
4643 ** the left operand of infix functions (the operand we want to
4644 ** control overloading) ends up as the second argument to the
4645 ** function. The expression "A glob B" is equivalent to
4646 ** "glob(B,A). We want to use the A in "A glob B" to test
4647 ** for function overloading. But we use the B term in "glob(B,A)".
4649 if( nFarg
>=2 && ExprHasProperty(pExpr
, EP_InfixFunc
) ){
4650 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[1].pExpr
);
4651 }else if( nFarg
>0 ){
4652 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[0].pExpr
);
4655 if( pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
){
4656 if( !pColl
) pColl
= db
->pDfltColl
;
4657 sqlite3VdbeAddOp4(v
, OP_CollSeq
, 0, 0, 0, (char *)pColl
, P4_COLLSEQ
);
4659 sqlite3VdbeAddFunctionCall(pParse
, constMask
, r1
, target
, nFarg
,
4663 sqlite3ReleaseTempRange(pParse
, r1
, nFarg
);
4665 sqlite3VdbeReleaseRegisters(pParse
, r1
, nFarg
, constMask
, 1);
4670 #ifndef SQLITE_OMIT_SUBQUERY
4674 testcase( op
==TK_EXISTS
);
4675 testcase( op
==TK_SELECT
);
4676 if( pParse
->db
->mallocFailed
){
4678 }else if( op
==TK_SELECT
4679 && ALWAYS( ExprUseXSelect(pExpr
) )
4680 && (nCol
= pExpr
->x
.pSelect
->pEList
->nExpr
)!=1
4682 sqlite3SubselectError(pParse
, nCol
, 1);
4684 return sqlite3CodeSubselect(pParse
, pExpr
);
4688 case TK_SELECT_COLUMN
: {
4690 Expr
*pLeft
= pExpr
->pLeft
;
4691 if( pLeft
->iTable
==0 || pParse
->withinRJSubrtn
> pLeft
->op2
){
4692 pLeft
->iTable
= sqlite3CodeSubselect(pParse
, pLeft
);
4693 pLeft
->op2
= pParse
->withinRJSubrtn
;
4695 assert( pLeft
->op
==TK_SELECT
|| pLeft
->op
==TK_ERROR
);
4696 n
= sqlite3ExprVectorSize(pLeft
);
4697 if( pExpr
->iTable
!=n
){
4698 sqlite3ErrorMsg(pParse
, "%d columns assigned %d values",
4701 return pLeft
->iTable
+ pExpr
->iColumn
;
4704 int destIfFalse
= sqlite3VdbeMakeLabel(pParse
);
4705 int destIfNull
= sqlite3VdbeMakeLabel(pParse
);
4706 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4707 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
4708 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
4709 sqlite3VdbeResolveLabel(v
, destIfFalse
);
4710 sqlite3VdbeAddOp2(v
, OP_AddImm
, target
, 0);
4711 sqlite3VdbeResolveLabel(v
, destIfNull
);
4714 #endif /* SQLITE_OMIT_SUBQUERY */
4718 ** x BETWEEN y AND z
4720 ** This is equivalent to
4724 ** X is stored in pExpr->pLeft.
4725 ** Y is stored in pExpr->pList->a[0].pExpr.
4726 ** Z is stored in pExpr->pList->a[1].pExpr.
4729 exprCodeBetween(pParse
, pExpr
, target
, 0, 0);
4733 if( !ExprHasProperty(pExpr
, EP_Collate
) ){
4734 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
4735 ** "SOFT-COLLATE" that is added to constraints that are pushed down
4736 ** from outer queries into sub-queries by the push-down optimization.
4737 ** Clear subtypes as subtypes may not cross a subquery boundary.
4739 assert( pExpr
->pLeft
);
4740 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
, target
);
4741 if( inReg
!=target
){
4742 sqlite3VdbeAddOp2(v
, OP_SCopy
, inReg
, target
);
4745 sqlite3VdbeAddOp1(v
, OP_ClrSubtype
, inReg
);
4748 pExpr
= pExpr
->pLeft
;
4749 goto expr_code_doover
; /* 2018-04-28: Prevent deep recursion. */
4754 pExpr
= pExpr
->pLeft
;
4755 goto expr_code_doover
; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4759 /* If the opcode is TK_TRIGGER, then the expression is a reference
4760 ** to a column in the new.* or old.* pseudo-tables available to
4761 ** trigger programs. In this case Expr.iTable is set to 1 for the
4762 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4763 ** is set to the column of the pseudo-table to read, or to -1 to
4764 ** read the rowid field.
4766 ** The expression is implemented using an OP_Param opcode. The p1
4767 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4768 ** to reference another column of the old.* pseudo-table, where
4769 ** i is the index of the column. For a new.rowid reference, p1 is
4770 ** set to (n+1), where n is the number of columns in each pseudo-table.
4771 ** For a reference to any other column in the new.* pseudo-table, p1
4772 ** is set to (n+2+i), where n and i are as defined previously. For
4773 ** example, if the table on which triggers are being fired is
4776 ** CREATE TABLE t1(a, b);
4778 ** Then p1 is interpreted as follows:
4780 ** p1==0 -> old.rowid p1==3 -> new.rowid
4781 ** p1==1 -> old.a p1==4 -> new.a
4782 ** p1==2 -> old.b p1==5 -> new.b
4788 assert( ExprUseYTab(pExpr
) );
4789 pTab
= pExpr
->y
.pTab
;
4790 iCol
= pExpr
->iColumn
;
4791 p1
= pExpr
->iTable
* (pTab
->nCol
+1) + 1
4792 + sqlite3TableColumnToStorage(pTab
, iCol
);
4794 assert( pExpr
->iTable
==0 || pExpr
->iTable
==1 );
4795 assert( iCol
>=-1 && iCol
<pTab
->nCol
);
4796 assert( pTab
->iPKey
<0 || iCol
!=pTab
->iPKey
);
4797 assert( p1
>=0 && p1
<(pTab
->nCol
*2+2) );
4799 sqlite3VdbeAddOp2(v
, OP_Param
, p1
, target
);
4800 VdbeComment((v
, "r[%d]=%s.%s", target
,
4801 (pExpr
->iTable
? "new" : "old"),
4802 (pExpr
->iColumn
<0 ? "rowid" : pExpr
->y
.pTab
->aCol
[iCol
].zCnName
)
4805 #ifndef SQLITE_OMIT_FLOATING_POINT
4806 /* If the column has REAL affinity, it may currently be stored as an
4807 ** integer. Use OP_RealAffinity to make sure it is really real.
4809 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
4810 ** floating point when extracting it from the record. */
4811 if( iCol
>=0 && pTab
->aCol
[iCol
].affinity
==SQLITE_AFF_REAL
){
4812 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4819 sqlite3ErrorMsg(pParse
, "row value misused");
4823 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
4824 ** that derive from the right-hand table of a LEFT JOIN. The
4825 ** Expr.iTable value is the table number for the right-hand table.
4826 ** The expression is only evaluated if that table is not currently
4827 ** on a LEFT JOIN NULL row.
4829 case TK_IF_NULL_ROW
: {
4831 u8 okConstFactor
= pParse
->okConstFactor
;
4832 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
4834 assert( pExpr
->iAgg
>=0 && pExpr
->iAgg
<pAggInfo
->nColumn
);
4835 if( !pAggInfo
->directMode
){
4836 inReg
= AggInfoColumnReg(pAggInfo
, pExpr
->iAgg
);
4839 if( pExpr
->pAggInfo
->useSortingIdx
){
4840 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
4841 pAggInfo
->aCol
[pExpr
->iAgg
].iSorterColumn
,
4847 addrINR
= sqlite3VdbeAddOp3(v
, OP_IfNullRow
, pExpr
->iTable
, 0, target
);
4848 /* The OP_IfNullRow opcode above can overwrite the result register with
4849 ** NULL. So we have to ensure that the result register is not a value
4850 ** that is suppose to be a constant. Two defenses are needed:
4851 ** (1) Temporarily disable factoring of constant expressions
4852 ** (2) Make sure the computed value really is stored in register
4853 ** "target" and not someplace else.
4855 pParse
->okConstFactor
= 0; /* note (1) above */
4856 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
, target
);
4857 pParse
->okConstFactor
= okConstFactor
;
4858 if( inReg
!=target
){ /* note (2) above */
4859 sqlite3VdbeAddOp2(v
, OP_SCopy
, inReg
, target
);
4862 sqlite3VdbeJumpHere(v
, addrINR
);
4868 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4871 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4873 ** Form A is can be transformed into the equivalent form B as follows:
4874 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
4875 ** WHEN x=eN THEN rN ELSE y END
4877 ** X (if it exists) is in pExpr->pLeft.
4878 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
4879 ** odd. The Y is also optional. If the number of elements in x.pList
4880 ** is even, then Y is omitted and the "otherwise" result is NULL.
4881 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
4883 ** The result of the expression is the Ri for the first matching Ei,
4884 ** or if there is no matching Ei, the ELSE term Y, or if there is
4885 ** no ELSE term, NULL.
4888 int endLabel
; /* GOTO label for end of CASE stmt */
4889 int nextCase
; /* GOTO label for next WHEN clause */
4890 int nExpr
; /* 2x number of WHEN terms */
4891 int i
; /* Loop counter */
4892 ExprList
*pEList
; /* List of WHEN terms */
4893 struct ExprList_item
*aListelem
; /* Array of WHEN terms */
4894 Expr opCompare
; /* The X==Ei expression */
4895 Expr
*pX
; /* The X expression */
4896 Expr
*pTest
= 0; /* X==Ei (form A) or just Ei (form B) */
4898 sqlite3
*db
= pParse
->db
;
4900 assert( ExprUseXList(pExpr
) && pExpr
->x
.pList
!=0 );
4901 assert(pExpr
->x
.pList
->nExpr
> 0);
4902 pEList
= pExpr
->x
.pList
;
4903 aListelem
= pEList
->a
;
4904 nExpr
= pEList
->nExpr
;
4905 endLabel
= sqlite3VdbeMakeLabel(pParse
);
4906 if( (pX
= pExpr
->pLeft
)!=0 ){
4907 pDel
= sqlite3ExprDup(db
, pX
, 0);
4908 if( db
->mallocFailed
){
4909 sqlite3ExprDelete(db
, pDel
);
4912 testcase( pX
->op
==TK_COLUMN
);
4913 exprToRegister(pDel
, exprCodeVector(pParse
, pDel
, ®Free1
));
4914 testcase( regFree1
==0 );
4915 memset(&opCompare
, 0, sizeof(opCompare
));
4916 opCompare
.op
= TK_EQ
;
4917 opCompare
.pLeft
= pDel
;
4919 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4920 ** The value in regFree1 might get SCopy-ed into the file result.
4921 ** So make sure that the regFree1 register is not reused for other
4922 ** purposes and possibly overwritten. */
4925 for(i
=0; i
<nExpr
-1; i
=i
+2){
4928 opCompare
.pRight
= aListelem
[i
].pExpr
;
4930 pTest
= aListelem
[i
].pExpr
;
4932 nextCase
= sqlite3VdbeMakeLabel(pParse
);
4933 testcase( pTest
->op
==TK_COLUMN
);
4934 sqlite3ExprIfFalse(pParse
, pTest
, nextCase
, SQLITE_JUMPIFNULL
);
4935 testcase( aListelem
[i
+1].pExpr
->op
==TK_COLUMN
);
4936 sqlite3ExprCode(pParse
, aListelem
[i
+1].pExpr
, target
);
4937 sqlite3VdbeGoto(v
, endLabel
);
4938 sqlite3VdbeResolveLabel(v
, nextCase
);
4941 sqlite3ExprCode(pParse
, pEList
->a
[nExpr
-1].pExpr
, target
);
4943 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4945 sqlite3ExprDelete(db
, pDel
);
4946 setDoNotMergeFlagOnCopy(v
);
4947 sqlite3VdbeResolveLabel(v
, endLabel
);
4950 #ifndef SQLITE_OMIT_TRIGGER
4952 assert( pExpr
->affExpr
==OE_Rollback
4953 || pExpr
->affExpr
==OE_Abort
4954 || pExpr
->affExpr
==OE_Fail
4955 || pExpr
->affExpr
==OE_Ignore
4957 if( !pParse
->pTriggerTab
&& !pParse
->nested
){
4958 sqlite3ErrorMsg(pParse
,
4959 "RAISE() may only be used within a trigger-program");
4962 if( pExpr
->affExpr
==OE_Abort
){
4963 sqlite3MayAbort(pParse
);
4965 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4966 if( pExpr
->affExpr
==OE_Ignore
){
4968 v
, OP_Halt
, SQLITE_OK
, OE_Ignore
, 0, pExpr
->u
.zToken
,0);
4971 sqlite3HaltConstraint(pParse
,
4972 pParse
->pTriggerTab
? SQLITE_CONSTRAINT_TRIGGER
: SQLITE_ERROR
,
4973 pExpr
->affExpr
, pExpr
->u
.zToken
, 0, 0);
4980 sqlite3ReleaseTempReg(pParse
, regFree1
);
4981 sqlite3ReleaseTempReg(pParse
, regFree2
);
4986 ** Generate code that will evaluate expression pExpr just one time
4987 ** per prepared statement execution.
4989 ** If the expression uses functions (that might throw an exception) then
4990 ** guard them with an OP_Once opcode to ensure that the code is only executed
4991 ** once. If no functions are involved, then factor the code out and put it at
4992 ** the end of the prepared statement in the initialization section.
4994 ** If regDest>=0 then the result is always stored in that register and the
4995 ** result is not reusable. If regDest<0 then this routine is free to
4996 ** store the value whereever it wants. The register where the expression
4997 ** is stored is returned. When regDest<0, two identical expressions might
4998 ** code to the same register, if they do not contain function calls and hence
4999 ** are factored out into the initialization section at the end of the
5000 ** prepared statement.
5002 int sqlite3ExprCodeRunJustOnce(
5003 Parse
*pParse
, /* Parsing context */
5004 Expr
*pExpr
, /* The expression to code when the VDBE initializes */
5005 int regDest
/* Store the value in this register */
5008 assert( ConstFactorOk(pParse
) );
5009 p
= pParse
->pConstExpr
;
5010 if( regDest
<0 && p
){
5011 struct ExprList_item
*pItem
;
5013 for(pItem
=p
->a
, i
=p
->nExpr
; i
>0; pItem
++, i
--){
5014 if( pItem
->fg
.reusable
5015 && sqlite3ExprCompare(0,pItem
->pExpr
,pExpr
,-1)==0
5017 return pItem
->u
.iConstExprReg
;
5021 pExpr
= sqlite3ExprDup(pParse
->db
, pExpr
, 0);
5022 if( pExpr
!=0 && ExprHasProperty(pExpr
, EP_HasFunc
) ){
5023 Vdbe
*v
= pParse
->pVdbe
;
5026 addr
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
5027 pParse
->okConstFactor
= 0;
5028 if( !pParse
->db
->mallocFailed
){
5029 if( regDest
<0 ) regDest
= ++pParse
->nMem
;
5030 sqlite3ExprCode(pParse
, pExpr
, regDest
);
5032 pParse
->okConstFactor
= 1;
5033 sqlite3ExprDelete(pParse
->db
, pExpr
);
5034 sqlite3VdbeJumpHere(v
, addr
);
5036 p
= sqlite3ExprListAppend(pParse
, p
, pExpr
);
5038 struct ExprList_item
*pItem
= &p
->a
[p
->nExpr
-1];
5039 pItem
->fg
.reusable
= regDest
<0;
5040 if( regDest
<0 ) regDest
= ++pParse
->nMem
;
5041 pItem
->u
.iConstExprReg
= regDest
;
5043 pParse
->pConstExpr
= p
;
5049 ** Generate code to evaluate an expression and store the results
5050 ** into a register. Return the register number where the results
5053 ** If the register is a temporary register that can be deallocated,
5054 ** then write its number into *pReg. If the result register is not
5055 ** a temporary, then set *pReg to zero.
5057 ** If pExpr is a constant, then this routine might generate this
5058 ** code to fill the register in the initialization section of the
5059 ** VDBE program, in order to factor it out of the evaluation loop.
5061 int sqlite3ExprCodeTemp(Parse
*pParse
, Expr
*pExpr
, int *pReg
){
5063 pExpr
= sqlite3ExprSkipCollateAndLikely(pExpr
);
5064 if( ConstFactorOk(pParse
)
5066 && pExpr
->op
!=TK_REGISTER
5067 && sqlite3ExprIsConstantNotJoin(pExpr
)
5070 r2
= sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, -1);
5072 int r1
= sqlite3GetTempReg(pParse
);
5073 r2
= sqlite3ExprCodeTarget(pParse
, pExpr
, r1
);
5077 sqlite3ReleaseTempReg(pParse
, r1
);
5085 ** Generate code that will evaluate expression pExpr and store the
5086 ** results in register target. The results are guaranteed to appear
5087 ** in register target.
5089 void sqlite3ExprCode(Parse
*pParse
, Expr
*pExpr
, int target
){
5092 assert( pExpr
==0 || !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
5093 assert( target
>0 && target
<=pParse
->nMem
);
5094 assert( pParse
->pVdbe
!=0 || pParse
->db
->mallocFailed
);
5095 if( pParse
->pVdbe
==0 ) return;
5096 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
);
5097 if( inReg
!=target
){
5099 if( ALWAYS(pExpr
) && ExprHasProperty(pExpr
,EP_Subquery
) ){
5104 sqlite3VdbeAddOp2(pParse
->pVdbe
, op
, inReg
, target
);
5109 ** Make a transient copy of expression pExpr and then code it using
5110 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5111 ** except that the input expression is guaranteed to be unchanged.
5113 void sqlite3ExprCodeCopy(Parse
*pParse
, Expr
*pExpr
, int target
){
5114 sqlite3
*db
= pParse
->db
;
5115 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
5116 if( !db
->mallocFailed
) sqlite3ExprCode(pParse
, pExpr
, target
);
5117 sqlite3ExprDelete(db
, pExpr
);
5121 ** Generate code that will evaluate expression pExpr and store the
5122 ** results in register target. The results are guaranteed to appear
5123 ** in register target. If the expression is constant, then this routine
5124 ** might choose to code the expression at initialization time.
5126 void sqlite3ExprCodeFactorable(Parse
*pParse
, Expr
*pExpr
, int target
){
5127 if( pParse
->okConstFactor
&& sqlite3ExprIsConstantNotJoin(pExpr
) ){
5128 sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, target
);
5130 sqlite3ExprCodeCopy(pParse
, pExpr
, target
);
5135 ** Generate code that pushes the value of every element of the given
5136 ** expression list into a sequence of registers beginning at target.
5138 ** Return the number of elements evaluated. The number returned will
5139 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5142 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5143 ** filled using OP_SCopy. OP_Copy must be used instead.
5145 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5146 ** factored out into initialization code.
5148 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5149 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5150 ** in registers at srcReg, and so the value can be copied from there.
5151 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5152 ** are simply omitted rather than being copied from srcReg.
5154 int sqlite3ExprCodeExprList(
5155 Parse
*pParse
, /* Parsing context */
5156 ExprList
*pList
, /* The expression list to be coded */
5157 int target
, /* Where to write results */
5158 int srcReg
, /* Source registers if SQLITE_ECEL_REF */
5159 u8 flags
/* SQLITE_ECEL_* flags */
5161 struct ExprList_item
*pItem
;
5163 u8 copyOp
= (flags
& SQLITE_ECEL_DUP
) ? OP_Copy
: OP_SCopy
;
5164 Vdbe
*v
= pParse
->pVdbe
;
5167 assert( pParse
->pVdbe
!=0 ); /* Never gets this far otherwise */
5169 if( !ConstFactorOk(pParse
) ) flags
&= ~SQLITE_ECEL_FACTOR
;
5170 for(pItem
=pList
->a
, i
=0; i
<n
; i
++, pItem
++){
5171 Expr
*pExpr
= pItem
->pExpr
;
5172 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5173 if( pItem
->fg
.bSorterRef
){
5178 if( (flags
& SQLITE_ECEL_REF
)!=0 && (j
= pItem
->u
.x
.iOrderByCol
)>0 ){
5179 if( flags
& SQLITE_ECEL_OMITREF
){
5183 sqlite3VdbeAddOp2(v
, copyOp
, j
+srcReg
-1, target
+i
);
5185 }else if( (flags
& SQLITE_ECEL_FACTOR
)!=0
5186 && sqlite3ExprIsConstantNotJoin(pExpr
)
5188 sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, target
+i
);
5190 int inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
+i
);
5191 if( inReg
!=target
+i
){
5194 && (pOp
=sqlite3VdbeGetLastOp(v
))->opcode
==OP_Copy
5195 && pOp
->p1
+pOp
->p3
+1==inReg
5196 && pOp
->p2
+pOp
->p3
+1==target
+i
5197 && pOp
->p5
==0 /* The do-not-merge flag must be clear */
5201 sqlite3VdbeAddOp2(v
, copyOp
, inReg
, target
+i
);
5210 ** Generate code for a BETWEEN operator.
5212 ** x BETWEEN y AND z
5214 ** The above is equivalent to
5218 ** Code it as such, taking care to do the common subexpression
5219 ** elimination of x.
5221 ** The xJumpIf parameter determines details:
5223 ** NULL: Store the boolean result in reg[dest]
5224 ** sqlite3ExprIfTrue: Jump to dest if true
5225 ** sqlite3ExprIfFalse: Jump to dest if false
5227 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5229 static void exprCodeBetween(
5230 Parse
*pParse
, /* Parsing and code generating context */
5231 Expr
*pExpr
, /* The BETWEEN expression */
5232 int dest
, /* Jump destination or storage location */
5233 void (*xJump
)(Parse
*,Expr
*,int,int), /* Action to take */
5234 int jumpIfNull
/* Take the jump if the BETWEEN is NULL */
5236 Expr exprAnd
; /* The AND operator in x>=y AND x<=z */
5237 Expr compLeft
; /* The x>=y term */
5238 Expr compRight
; /* The x<=z term */
5239 int regFree1
= 0; /* Temporary use register */
5241 sqlite3
*db
= pParse
->db
;
5243 memset(&compLeft
, 0, sizeof(Expr
));
5244 memset(&compRight
, 0, sizeof(Expr
));
5245 memset(&exprAnd
, 0, sizeof(Expr
));
5247 assert( ExprUseXList(pExpr
) );
5248 pDel
= sqlite3ExprDup(db
, pExpr
->pLeft
, 0);
5249 if( db
->mallocFailed
==0 ){
5250 exprAnd
.op
= TK_AND
;
5251 exprAnd
.pLeft
= &compLeft
;
5252 exprAnd
.pRight
= &compRight
;
5253 compLeft
.op
= TK_GE
;
5254 compLeft
.pLeft
= pDel
;
5255 compLeft
.pRight
= pExpr
->x
.pList
->a
[0].pExpr
;
5256 compRight
.op
= TK_LE
;
5257 compRight
.pLeft
= pDel
;
5258 compRight
.pRight
= pExpr
->x
.pList
->a
[1].pExpr
;
5259 exprToRegister(pDel
, exprCodeVector(pParse
, pDel
, ®Free1
));
5261 xJump(pParse
, &exprAnd
, dest
, jumpIfNull
);
5263 /* Mark the expression is being from the ON or USING clause of a join
5264 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5265 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5266 ** for clarity, but we are out of bits in the Expr.flags field so we
5267 ** have to reuse the EP_OuterON bit. Bummer. */
5268 pDel
->flags
|= EP_OuterON
;
5269 sqlite3ExprCodeTarget(pParse
, &exprAnd
, dest
);
5271 sqlite3ReleaseTempReg(pParse
, regFree1
);
5273 sqlite3ExprDelete(db
, pDel
);
5275 /* Ensure adequate test coverage */
5276 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
==0 && regFree1
==0 );
5277 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
==0 && regFree1
!=0 );
5278 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
!=0 && regFree1
==0 );
5279 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
!=0 && regFree1
!=0 );
5280 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
==0 && regFree1
==0 );
5281 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
==0 && regFree1
!=0 );
5282 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
!=0 && regFree1
==0 );
5283 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
!=0 && regFree1
!=0 );
5284 testcase( xJump
==0 );
5288 ** Generate code for a boolean expression such that a jump is made
5289 ** to the label "dest" if the expression is true but execution
5290 ** continues straight thru if the expression is false.
5292 ** If the expression evaluates to NULL (neither true nor false), then
5293 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5295 ** This code depends on the fact that certain token values (ex: TK_EQ)
5296 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5297 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5298 ** the make process cause these values to align. Assert()s in the code
5299 ** below verify that the numbers are aligned correctly.
5301 void sqlite3ExprIfTrue(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
5302 Vdbe
*v
= pParse
->pVdbe
;
5308 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
5309 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
5310 if( NEVER(pExpr
==0) ) return; /* No way this can happen */
5311 assert( !ExprHasVVAProperty(pExpr
, EP_Immutable
) );
5316 Expr
*pAlt
= sqlite3ExprSimplifiedAndOr(pExpr
);
5318 sqlite3ExprIfTrue(pParse
, pAlt
, dest
, jumpIfNull
);
5319 }else if( op
==TK_AND
){
5320 int d2
= sqlite3VdbeMakeLabel(pParse
);
5321 testcase( jumpIfNull
==0 );
5322 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, d2
,
5323 jumpIfNull
^SQLITE_JUMPIFNULL
);
5324 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5325 sqlite3VdbeResolveLabel(v
, d2
);
5327 testcase( jumpIfNull
==0 );
5328 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5329 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5334 testcase( jumpIfNull
==0 );
5335 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5339 int isNot
; /* IS NOT TRUE or IS NOT FALSE */
5340 int isTrue
; /* IS TRUE or IS NOT TRUE */
5341 testcase( jumpIfNull
==0 );
5342 isNot
= pExpr
->op2
==TK_ISNOT
;
5343 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
5344 testcase( isTrue
&& isNot
);
5345 testcase( !isTrue
&& isNot
);
5346 if( isTrue
^ isNot
){
5347 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
,
5348 isNot
? SQLITE_JUMPIFNULL
: 0);
5350 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
,
5351 isNot
? SQLITE_JUMPIFNULL
: 0);
5357 testcase( op
==TK_IS
);
5358 testcase( op
==TK_ISNOT
);
5359 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
5360 jumpIfNull
= SQLITE_NULLEQ
;
5361 /* no break */ deliberate_fall_through
5368 if( sqlite3ExprIsVector(pExpr
->pLeft
) ) goto default_expr
;
5369 testcase( jumpIfNull
==0 );
5370 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5371 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
5372 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
5373 r1
, r2
, dest
, jumpIfNull
, ExprHasProperty(pExpr
,EP_Commuted
));
5374 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
5375 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
5376 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
5377 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
5378 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
);
5379 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
==SQLITE_NULLEQ
);
5380 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
!=SQLITE_NULLEQ
);
5381 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
);
5382 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
==SQLITE_NULLEQ
);
5383 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
!=SQLITE_NULLEQ
);
5384 testcase( regFree1
==0 );
5385 testcase( regFree2
==0 );
5390 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
5391 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
5392 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5393 sqlite3VdbeTypeofColumn(v
, r1
);
5394 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
5395 VdbeCoverageIf(v
, op
==TK_ISNULL
);
5396 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
5397 testcase( regFree1
==0 );
5401 testcase( jumpIfNull
==0 );
5402 exprCodeBetween(pParse
, pExpr
, dest
, sqlite3ExprIfTrue
, jumpIfNull
);
5405 #ifndef SQLITE_OMIT_SUBQUERY
5407 int destIfFalse
= sqlite3VdbeMakeLabel(pParse
);
5408 int destIfNull
= jumpIfNull
? dest
: destIfFalse
;
5409 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
5410 sqlite3VdbeGoto(v
, dest
);
5411 sqlite3VdbeResolveLabel(v
, destIfFalse
);
5417 if( ExprAlwaysTrue(pExpr
) ){
5418 sqlite3VdbeGoto(v
, dest
);
5419 }else if( ExprAlwaysFalse(pExpr
) ){
5422 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
5423 sqlite3VdbeAddOp3(v
, OP_If
, r1
, dest
, jumpIfNull
!=0);
5425 testcase( regFree1
==0 );
5426 testcase( jumpIfNull
==0 );
5431 sqlite3ReleaseTempReg(pParse
, regFree1
);
5432 sqlite3ReleaseTempReg(pParse
, regFree2
);
5436 ** Generate code for a boolean expression such that a jump is made
5437 ** to the label "dest" if the expression is false but execution
5438 ** continues straight thru if the expression is true.
5440 ** If the expression evaluates to NULL (neither true nor false) then
5441 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5444 void sqlite3ExprIfFalse(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
5445 Vdbe
*v
= pParse
->pVdbe
;
5451 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
5452 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
5453 if( pExpr
==0 ) return;
5454 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
5456 /* The value of pExpr->op and op are related as follows:
5459 ** --------- ----------
5460 ** TK_ISNULL OP_NotNull
5461 ** TK_NOTNULL OP_IsNull
5469 ** For other values of pExpr->op, op is undefined and unused.
5470 ** The value of TK_ and OP_ constants are arranged such that we
5471 ** can compute the mapping above using the following expression.
5472 ** Assert()s verify that the computation is correct.
5474 op
= ((pExpr
->op
+(TK_ISNULL
&1))^1)-(TK_ISNULL
&1);
5476 /* Verify correct alignment of TK_ and OP_ constants
5478 assert( pExpr
->op
!=TK_ISNULL
|| op
==OP_NotNull
);
5479 assert( pExpr
->op
!=TK_NOTNULL
|| op
==OP_IsNull
);
5480 assert( pExpr
->op
!=TK_NE
|| op
==OP_Eq
);
5481 assert( pExpr
->op
!=TK_EQ
|| op
==OP_Ne
);
5482 assert( pExpr
->op
!=TK_LT
|| op
==OP_Ge
);
5483 assert( pExpr
->op
!=TK_LE
|| op
==OP_Gt
);
5484 assert( pExpr
->op
!=TK_GT
|| op
==OP_Le
);
5485 assert( pExpr
->op
!=TK_GE
|| op
==OP_Lt
);
5487 switch( pExpr
->op
){
5490 Expr
*pAlt
= sqlite3ExprSimplifiedAndOr(pExpr
);
5492 sqlite3ExprIfFalse(pParse
, pAlt
, dest
, jumpIfNull
);
5493 }else if( pExpr
->op
==TK_AND
){
5494 testcase( jumpIfNull
==0 );
5495 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5496 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5498 int d2
= sqlite3VdbeMakeLabel(pParse
);
5499 testcase( jumpIfNull
==0 );
5500 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, d2
,
5501 jumpIfNull
^SQLITE_JUMPIFNULL
);
5502 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5503 sqlite3VdbeResolveLabel(v
, d2
);
5508 testcase( jumpIfNull
==0 );
5509 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5513 int isNot
; /* IS NOT TRUE or IS NOT FALSE */
5514 int isTrue
; /* IS TRUE or IS NOT TRUE */
5515 testcase( jumpIfNull
==0 );
5516 isNot
= pExpr
->op2
==TK_ISNOT
;
5517 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
5518 testcase( isTrue
&& isNot
);
5519 testcase( !isTrue
&& isNot
);
5520 if( isTrue
^ isNot
){
5521 /* IS TRUE and IS NOT FALSE */
5522 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
,
5523 isNot
? 0 : SQLITE_JUMPIFNULL
);
5526 /* IS FALSE and IS NOT TRUE */
5527 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
,
5528 isNot
? 0 : SQLITE_JUMPIFNULL
);
5534 testcase( pExpr
->op
==TK_IS
);
5535 testcase( pExpr
->op
==TK_ISNOT
);
5536 op
= (pExpr
->op
==TK_IS
) ? TK_NE
: TK_EQ
;
5537 jumpIfNull
= SQLITE_NULLEQ
;
5538 /* no break */ deliberate_fall_through
5545 if( sqlite3ExprIsVector(pExpr
->pLeft
) ) goto default_expr
;
5546 testcase( jumpIfNull
==0 );
5547 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5548 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
5549 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
5550 r1
, r2
, dest
, jumpIfNull
,ExprHasProperty(pExpr
,EP_Commuted
));
5551 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
5552 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
5553 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
5554 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
5555 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
);
5556 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
!=SQLITE_NULLEQ
);
5557 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
==SQLITE_NULLEQ
);
5558 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
);
5559 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
!=SQLITE_NULLEQ
);
5560 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
==SQLITE_NULLEQ
);
5561 testcase( regFree1
==0 );
5562 testcase( regFree2
==0 );
5567 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5568 sqlite3VdbeTypeofColumn(v
, r1
);
5569 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
5570 testcase( op
==TK_ISNULL
); VdbeCoverageIf(v
, op
==TK_ISNULL
);
5571 testcase( op
==TK_NOTNULL
); VdbeCoverageIf(v
, op
==TK_NOTNULL
);
5572 testcase( regFree1
==0 );
5576 testcase( jumpIfNull
==0 );
5577 exprCodeBetween(pParse
, pExpr
, dest
, sqlite3ExprIfFalse
, jumpIfNull
);
5580 #ifndef SQLITE_OMIT_SUBQUERY
5583 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, dest
);
5585 int destIfNull
= sqlite3VdbeMakeLabel(pParse
);
5586 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, destIfNull
);
5587 sqlite3VdbeResolveLabel(v
, destIfNull
);
5594 if( ExprAlwaysFalse(pExpr
) ){
5595 sqlite3VdbeGoto(v
, dest
);
5596 }else if( ExprAlwaysTrue(pExpr
) ){
5599 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
5600 sqlite3VdbeAddOp3(v
, OP_IfNot
, r1
, dest
, jumpIfNull
!=0);
5602 testcase( regFree1
==0 );
5603 testcase( jumpIfNull
==0 );
5608 sqlite3ReleaseTempReg(pParse
, regFree1
);
5609 sqlite3ReleaseTempReg(pParse
, regFree2
);
5613 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5614 ** code generation, and that copy is deleted after code generation. This
5615 ** ensures that the original pExpr is unchanged.
5617 void sqlite3ExprIfFalseDup(Parse
*pParse
, Expr
*pExpr
, int dest
,int jumpIfNull
){
5618 sqlite3
*db
= pParse
->db
;
5619 Expr
*pCopy
= sqlite3ExprDup(db
, pExpr
, 0);
5620 if( db
->mallocFailed
==0 ){
5621 sqlite3ExprIfFalse(pParse
, pCopy
, dest
, jumpIfNull
);
5623 sqlite3ExprDelete(db
, pCopy
);
5627 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5628 ** type of expression.
5630 ** If pExpr is a simple SQL value - an integer, real, string, blob
5631 ** or NULL value - then the VDBE currently being prepared is configured
5632 ** to re-prepare each time a new value is bound to variable pVar.
5634 ** Additionally, if pExpr is a simple SQL value and the value is the
5635 ** same as that currently bound to variable pVar, non-zero is returned.
5636 ** Otherwise, if the values are not the same or if pExpr is not a simple
5637 ** SQL value, zero is returned.
5639 static int exprCompareVariable(
5640 const Parse
*pParse
,
5646 sqlite3_value
*pL
, *pR
= 0;
5648 sqlite3ValueFromExpr(pParse
->db
, pExpr
, SQLITE_UTF8
, SQLITE_AFF_BLOB
, &pR
);
5650 iVar
= pVar
->iColumn
;
5651 sqlite3VdbeSetVarmask(pParse
->pVdbe
, iVar
);
5652 pL
= sqlite3VdbeGetBoundValue(pParse
->pReprepare
, iVar
, SQLITE_AFF_BLOB
);
5654 if( sqlite3_value_type(pL
)==SQLITE_TEXT
){
5655 sqlite3_value_text(pL
); /* Make sure the encoding is UTF-8 */
5657 res
= 0==sqlite3MemCompare(pL
, pR
, 0);
5659 sqlite3ValueFree(pR
);
5660 sqlite3ValueFree(pL
);
5667 ** Do a deep comparison of two expression trees. Return 0 if the two
5668 ** expressions are completely identical. Return 1 if they differ only
5669 ** by a COLLATE operator at the top level. Return 2 if there are differences
5670 ** other than the top-level COLLATE operator.
5672 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5673 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5675 ** The pA side might be using TK_REGISTER. If that is the case and pB is
5676 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5678 ** Sometimes this routine will return 2 even if the two expressions
5679 ** really are equivalent. If we cannot prove that the expressions are
5680 ** identical, we return 2 just to be safe. So if this routine
5681 ** returns 2, then you do not really know for certain if the two
5682 ** expressions are the same. But if you get a 0 or 1 return, then you
5683 ** can be sure the expressions are the same. In the places where
5684 ** this routine is used, it does not hurt to get an extra 2 - that
5685 ** just might result in some slightly slower code. But returning
5686 ** an incorrect 0 or 1 could lead to a malfunction.
5688 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5689 ** pParse->pReprepare can be matched against literals in pB. The
5690 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5691 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5692 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5693 ** pB causes a return value of 2.
5695 int sqlite3ExprCompare(
5696 const Parse
*pParse
,
5702 if( pA
==0 || pB
==0 ){
5703 return pB
==pA
? 0 : 2;
5705 if( pParse
&& pA
->op
==TK_VARIABLE
&& exprCompareVariable(pParse
, pA
, pB
) ){
5708 combinedFlags
= pA
->flags
| pB
->flags
;
5709 if( combinedFlags
& EP_IntValue
){
5710 if( (pA
->flags
&pB
->flags
&EP_IntValue
)!=0 && pA
->u
.iValue
==pB
->u
.iValue
){
5715 if( pA
->op
!=pB
->op
|| pA
->op
==TK_RAISE
){
5716 if( pA
->op
==TK_COLLATE
&& sqlite3ExprCompare(pParse
, pA
->pLeft
,pB
,iTab
)<2 ){
5719 if( pB
->op
==TK_COLLATE
&& sqlite3ExprCompare(pParse
, pA
,pB
->pLeft
,iTab
)<2 ){
5722 if( pA
->op
==TK_AGG_COLUMN
&& pB
->op
==TK_COLUMN
5723 && pB
->iTable
<0 && pA
->iTable
==iTab
5730 assert( !ExprHasProperty(pA
, EP_IntValue
) );
5731 assert( !ExprHasProperty(pB
, EP_IntValue
) );
5733 if( pA
->op
==TK_FUNCTION
|| pA
->op
==TK_AGG_FUNCTION
){
5734 if( sqlite3StrICmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ) return 2;
5735 #ifndef SQLITE_OMIT_WINDOWFUNC
5736 assert( pA
->op
==pB
->op
);
5737 if( ExprHasProperty(pA
,EP_WinFunc
)!=ExprHasProperty(pB
,EP_WinFunc
) ){
5740 if( ExprHasProperty(pA
,EP_WinFunc
) ){
5741 if( sqlite3WindowCompare(pParse
, pA
->y
.pWin
, pB
->y
.pWin
, 1)!=0 ){
5746 }else if( pA
->op
==TK_NULL
){
5748 }else if( pA
->op
==TK_COLLATE
){
5749 if( sqlite3_stricmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ) return 2;
5752 && pA
->op
!=TK_COLUMN
5753 && pA
->op
!=TK_AGG_COLUMN
5754 && strcmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0
5759 if( (pA
->flags
& (EP_Distinct
|EP_Commuted
))
5760 != (pB
->flags
& (EP_Distinct
|EP_Commuted
)) ) return 2;
5761 if( ALWAYS((combinedFlags
& EP_TokenOnly
)==0) ){
5762 if( combinedFlags
& EP_xIsSelect
) return 2;
5763 if( (combinedFlags
& EP_FixedCol
)==0
5764 && sqlite3ExprCompare(pParse
, pA
->pLeft
, pB
->pLeft
, iTab
) ) return 2;
5765 if( sqlite3ExprCompare(pParse
, pA
->pRight
, pB
->pRight
, iTab
) ) return 2;
5766 if( sqlite3ExprListCompare(pA
->x
.pList
, pB
->x
.pList
, iTab
) ) return 2;
5767 if( pA
->op
!=TK_STRING
5768 && pA
->op
!=TK_TRUEFALSE
5769 && ALWAYS((combinedFlags
& EP_Reduced
)==0)
5771 if( pA
->iColumn
!=pB
->iColumn
) return 2;
5772 if( pA
->op2
!=pB
->op2
&& pA
->op
==TK_TRUTH
) return 2;
5773 if( pA
->op
!=TK_IN
&& pA
->iTable
!=pB
->iTable
&& pA
->iTable
!=iTab
){
5782 ** Compare two ExprList objects. Return 0 if they are identical, 1
5783 ** if they are certainly different, or 2 if it is not possible to
5784 ** determine if they are identical or not.
5786 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5787 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5789 ** This routine might return non-zero for equivalent ExprLists. The
5790 ** only consequence will be disabled optimizations. But this routine
5791 ** must never return 0 if the two ExprList objects are different, or
5792 ** a malfunction will result.
5794 ** Two NULL pointers are considered to be the same. But a NULL pointer
5795 ** always differs from a non-NULL pointer.
5797 int sqlite3ExprListCompare(const ExprList
*pA
, const ExprList
*pB
, int iTab
){
5799 if( pA
==0 && pB
==0 ) return 0;
5800 if( pA
==0 || pB
==0 ) return 1;
5801 if( pA
->nExpr
!=pB
->nExpr
) return 1;
5802 for(i
=0; i
<pA
->nExpr
; i
++){
5804 Expr
*pExprA
= pA
->a
[i
].pExpr
;
5805 Expr
*pExprB
= pB
->a
[i
].pExpr
;
5806 if( pA
->a
[i
].fg
.sortFlags
!=pB
->a
[i
].fg
.sortFlags
) return 1;
5807 if( (res
= sqlite3ExprCompare(0, pExprA
, pExprB
, iTab
)) ) return res
;
5813 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
5816 int sqlite3ExprCompareSkip(Expr
*pA
,Expr
*pB
, int iTab
){
5817 return sqlite3ExprCompare(0,
5818 sqlite3ExprSkipCollateAndLikely(pA
),
5819 sqlite3ExprSkipCollateAndLikely(pB
),
5824 ** Return non-zero if Expr p can only be true if pNN is not NULL.
5826 ** Or if seenNot is true, return non-zero if Expr p can only be
5827 ** non-NULL if pNN is not NULL
5829 static int exprImpliesNotNull(
5830 const Parse
*pParse
,/* Parsing context */
5831 const Expr
*p
, /* The expression to be checked */
5832 const Expr
*pNN
, /* The expression that is NOT NULL */
5833 int iTab
, /* Table being evaluated */
5834 int seenNot
/* Return true only if p can be any non-NULL value */
5838 if( sqlite3ExprCompare(pParse
, p
, pNN
, iTab
)==0 ){
5839 return pNN
->op
!=TK_NULL
;
5843 if( seenNot
&& ExprHasProperty(p
, EP_xIsSelect
) ) return 0;
5844 assert( ExprUseXSelect(p
) || (p
->x
.pList
!=0 && p
->x
.pList
->nExpr
>0) );
5845 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
5849 assert( ExprUseXList(p
) );
5852 assert( pList
->nExpr
==2 );
5853 if( seenNot
) return 0;
5854 if( exprImpliesNotNull(pParse
, pList
->a
[0].pExpr
, pNN
, iTab
, 1)
5855 || exprImpliesNotNull(pParse
, pList
->a
[1].pExpr
, pNN
, iTab
, 1)
5859 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
5874 /* no break */ deliberate_fall_through
5879 if( exprImpliesNotNull(pParse
, p
->pRight
, pNN
, iTab
, seenNot
) ) return 1;
5880 /* no break */ deliberate_fall_through
5886 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, seenNot
);
5889 if( seenNot
) return 0;
5890 if( p
->op2
!=TK_IS
) return 0;
5891 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
5895 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
5902 ** Return true if we can prove the pE2 will always be true if pE1 is
5903 ** true. Return false if we cannot complete the proof or if pE2 might
5904 ** be false. Examples:
5906 ** pE1: x==5 pE2: x==5 Result: true
5907 ** pE1: x>0 pE2: x==5 Result: false
5908 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
5909 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
5910 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
5911 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
5912 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
5914 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
5915 ** Expr.iTable<0 then assume a table number given by iTab.
5917 ** If pParse is not NULL, then the values of bound variables in pE1 are
5918 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
5919 ** modified to record which bound variables are referenced. If pParse
5920 ** is NULL, then false will be returned if pE1 contains any bound variables.
5922 ** When in doubt, return false. Returning true might give a performance
5923 ** improvement. Returning false might cause a performance reduction, but
5924 ** it will always give the correct answer and is hence always safe.
5926 int sqlite3ExprImpliesExpr(
5927 const Parse
*pParse
,
5932 if( sqlite3ExprCompare(pParse
, pE1
, pE2
, iTab
)==0 ){
5936 && (sqlite3ExprImpliesExpr(pParse
, pE1
, pE2
->pLeft
, iTab
)
5937 || sqlite3ExprImpliesExpr(pParse
, pE1
, pE2
->pRight
, iTab
) )
5941 if( pE2
->op
==TK_NOTNULL
5942 && exprImpliesNotNull(pParse
, pE1
, pE2
->pLeft
, iTab
, 0)
5950 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
5951 ** If the expression node requires that the table at pWalker->iCur
5952 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
5954 ** This routine controls an optimization. False positives (setting
5955 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
5956 ** (never setting pWalker->eCode) is a harmless missed optimization.
5958 static int impliesNotNullRow(Walker
*pWalker
, Expr
*pExpr
){
5959 testcase( pExpr
->op
==TK_AGG_COLUMN
);
5960 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
5961 if( ExprHasProperty(pExpr
, EP_OuterON
) ) return WRC_Prune
;
5962 switch( pExpr
->op
){
5973 testcase( pExpr
->op
==TK_ISNOT
);
5974 testcase( pExpr
->op
==TK_ISNULL
);
5975 testcase( pExpr
->op
==TK_NOTNULL
);
5976 testcase( pExpr
->op
==TK_IS
);
5977 testcase( pExpr
->op
==TK_OR
);
5978 testcase( pExpr
->op
==TK_VECTOR
);
5979 testcase( pExpr
->op
==TK_CASE
);
5980 testcase( pExpr
->op
==TK_IN
);
5981 testcase( pExpr
->op
==TK_FUNCTION
);
5982 testcase( pExpr
->op
==TK_TRUTH
);
5985 if( pWalker
->u
.iCur
==pExpr
->iTable
){
5992 if( pWalker
->eCode
==0 ){
5993 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
5994 if( pWalker
->eCode
){
5996 sqlite3WalkExpr(pWalker
, pExpr
->pRight
);
6002 if( sqlite3WalkExpr(pWalker
, pExpr
->pLeft
)==WRC_Abort
){
6003 assert( pWalker
->eCode
);
6008 /* Virtual tables are allowed to use constraints like x=NULL. So
6009 ** a term of the form x=y does not prove that y is not null if x
6010 ** is the column of a virtual table */
6017 Expr
*pLeft
= pExpr
->pLeft
;
6018 Expr
*pRight
= pExpr
->pRight
;
6019 testcase( pExpr
->op
==TK_EQ
);
6020 testcase( pExpr
->op
==TK_NE
);
6021 testcase( pExpr
->op
==TK_LT
);
6022 testcase( pExpr
->op
==TK_LE
);
6023 testcase( pExpr
->op
==TK_GT
);
6024 testcase( pExpr
->op
==TK_GE
);
6025 /* The y.pTab=0 assignment in wherecode.c always happens after the
6026 ** impliesNotNullRow() test */
6027 assert( pLeft
->op
!=TK_COLUMN
|| ExprUseYTab(pLeft
) );
6028 assert( pRight
->op
!=TK_COLUMN
|| ExprUseYTab(pRight
) );
6029 if( (pLeft
->op
==TK_COLUMN
6030 && ALWAYS(pLeft
->y
.pTab
!=0)
6031 && IsVirtual(pLeft
->y
.pTab
))
6032 || (pRight
->op
==TK_COLUMN
6033 && ALWAYS(pRight
->y
.pTab
!=0)
6034 && IsVirtual(pRight
->y
.pTab
))
6038 /* no break */ deliberate_fall_through
6041 return WRC_Continue
;
6046 ** Return true (non-zero) if expression p can only be true if at least
6047 ** one column of table iTab is non-null. In other words, return true
6048 ** if expression p will always be NULL or false if every column of iTab
6051 ** False negatives are acceptable. In other words, it is ok to return
6052 ** zero even if expression p will never be true of every column of iTab
6053 ** is NULL. A false negative is merely a missed optimization opportunity.
6055 ** False positives are not allowed, however. A false positive may result
6056 ** in an incorrect answer.
6058 ** Terms of p that are marked with EP_OuterON (and hence that come from
6059 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6061 ** This routine is used to check if a LEFT JOIN can be converted into
6062 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6063 ** clause requires that some column of the right table of the LEFT JOIN
6064 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6067 int sqlite3ExprImpliesNonNullRow(Expr
*p
, int iTab
){
6069 p
= sqlite3ExprSkipCollateAndLikely(p
);
6070 if( p
==0 ) return 0;
6071 if( p
->op
==TK_NOTNULL
){
6074 while( p
->op
==TK_AND
){
6075 if( sqlite3ExprImpliesNonNullRow(p
->pLeft
, iTab
) ) return 1;
6079 w
.xExprCallback
= impliesNotNullRow
;
6080 w
.xSelectCallback
= 0;
6081 w
.xSelectCallback2
= 0;
6084 sqlite3WalkExpr(&w
, p
);
6089 ** An instance of the following structure is used by the tree walker
6090 ** to determine if an expression can be evaluated by reference to the
6091 ** index only, without having to do a search for the corresponding
6092 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6093 ** is the cursor for the table.
6096 Index
*pIdx
; /* The index to be tested for coverage */
6097 int iCur
; /* Cursor number for the table corresponding to the index */
6101 ** Check to see if there are references to columns in table
6102 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6103 ** pWalker->u.pIdxCover->pIdx.
6105 static int exprIdxCover(Walker
*pWalker
, Expr
*pExpr
){
6106 if( pExpr
->op
==TK_COLUMN
6107 && pExpr
->iTable
==pWalker
->u
.pIdxCover
->iCur
6108 && sqlite3TableColumnToIndex(pWalker
->u
.pIdxCover
->pIdx
, pExpr
->iColumn
)<0
6113 return WRC_Continue
;
6117 ** Determine if an index pIdx on table with cursor iCur contains will
6118 ** the expression pExpr. Return true if the index does cover the
6119 ** expression and false if the pExpr expression references table columns
6120 ** that are not found in the index pIdx.
6122 ** An index covering an expression means that the expression can be
6123 ** evaluated using only the index and without having to lookup the
6124 ** corresponding table entry.
6126 int sqlite3ExprCoveredByIndex(
6127 Expr
*pExpr
, /* The index to be tested */
6128 int iCur
, /* The cursor number for the corresponding table */
6129 Index
*pIdx
/* The index that might be used for coverage */
6132 struct IdxCover xcov
;
6133 memset(&w
, 0, sizeof(w
));
6136 w
.xExprCallback
= exprIdxCover
;
6137 w
.u
.pIdxCover
= &xcov
;
6138 sqlite3WalkExpr(&w
, pExpr
);
6143 /* Structure used to pass information throught the Walker in order to
6144 ** implement sqlite3ReferencesSrcList().
6147 sqlite3
*db
; /* Database connection used for sqlite3DbRealloc() */
6148 SrcList
*pRef
; /* Looking for references to these tables */
6149 i64 nExclude
; /* Number of tables to exclude from the search */
6150 int *aiExclude
; /* Cursor IDs for tables to exclude from the search */
6154 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6156 ** When entering a new subquery on the pExpr argument, add all FROM clause
6157 ** entries for that subquery to the exclude list.
6159 ** When leaving the subquery, remove those entries from the exclude list.
6161 static int selectRefEnter(Walker
*pWalker
, Select
*pSelect
){
6162 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6163 SrcList
*pSrc
= pSelect
->pSrc
;
6166 if( pSrc
->nSrc
==0 ) return WRC_Continue
;
6168 p
->nExclude
+= pSrc
->nSrc
;
6169 piNew
= sqlite3DbRealloc(p
->db
, p
->aiExclude
, p
->nExclude
*sizeof(int));
6174 p
->aiExclude
= piNew
;
6176 for(i
=0; i
<pSrc
->nSrc
; i
++, j
++){
6177 p
->aiExclude
[j
] = pSrc
->a
[i
].iCursor
;
6179 return WRC_Continue
;
6181 static void selectRefLeave(Walker
*pWalker
, Select
*pSelect
){
6182 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6183 SrcList
*pSrc
= pSelect
->pSrc
;
6185 assert( p
->nExclude
>=pSrc
->nSrc
);
6186 p
->nExclude
-= pSrc
->nSrc
;
6190 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6192 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6193 ** of the tables shown in RefSrcList.pRef.
6195 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6196 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6198 static int exprRefToSrcList(Walker
*pWalker
, Expr
*pExpr
){
6199 if( pExpr
->op
==TK_COLUMN
6200 || pExpr
->op
==TK_AGG_COLUMN
6203 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6204 SrcList
*pSrc
= p
->pRef
;
6205 int nSrc
= pSrc
? pSrc
->nSrc
: 0;
6206 for(i
=0; i
<nSrc
; i
++){
6207 if( pExpr
->iTable
==pSrc
->a
[i
].iCursor
){
6208 pWalker
->eCode
|= 1;
6209 return WRC_Continue
;
6212 for(i
=0; i
<p
->nExclude
&& p
->aiExclude
[i
]!=pExpr
->iTable
; i
++){}
6213 if( i
>=p
->nExclude
){
6214 pWalker
->eCode
|= 2;
6217 return WRC_Continue
;
6221 ** Check to see if pExpr references any tables in pSrcList.
6222 ** Possible return values:
6224 ** 1 pExpr does references a table in pSrcList.
6226 ** 0 pExpr references some table that is not defined in either
6227 ** pSrcList or in subqueries of pExpr itself.
6229 ** -1 pExpr only references no tables at all, or it only
6230 ** references tables defined in subqueries of pExpr itself.
6232 ** As currently used, pExpr is always an aggregate function call. That
6233 ** fact is exploited for efficiency.
6235 int sqlite3ReferencesSrcList(Parse
*pParse
, Expr
*pExpr
, SrcList
*pSrcList
){
6237 struct RefSrcList x
;
6238 assert( pParse
->db
!=0 );
6239 memset(&w
, 0, sizeof(w
));
6240 memset(&x
, 0, sizeof(x
));
6241 w
.xExprCallback
= exprRefToSrcList
;
6242 w
.xSelectCallback
= selectRefEnter
;
6243 w
.xSelectCallback2
= selectRefLeave
;
6244 w
.u
.pRefSrcList
= &x
;
6247 assert( pExpr
->op
==TK_AGG_FUNCTION
);
6248 assert( ExprUseXList(pExpr
) );
6249 sqlite3WalkExprList(&w
, pExpr
->x
.pList
);
6250 #ifndef SQLITE_OMIT_WINDOWFUNC
6251 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
6252 sqlite3WalkExpr(&w
, pExpr
->y
.pWin
->pFilter
);
6255 if( x
.aiExclude
) sqlite3DbNNFreeNN(pParse
->db
, x
.aiExclude
);
6256 if( w
.eCode
& 0x01 ){
6258 }else if( w
.eCode
){
6266 ** This is a Walker expression node callback.
6268 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6269 ** object that is referenced does not refer directly to the Expr. If
6270 ** it does, make a copy. This is done because the pExpr argument is
6271 ** subject to change.
6273 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6274 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6276 static int agginfoPersistExprCb(Walker
*pWalker
, Expr
*pExpr
){
6277 if( ALWAYS(!ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
))
6278 && pExpr
->pAggInfo
!=0
6280 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
6281 int iAgg
= pExpr
->iAgg
;
6282 Parse
*pParse
= pWalker
->pParse
;
6283 sqlite3
*db
= pParse
->db
;
6284 if( pExpr
->op
!=TK_AGG_FUNCTION
){
6285 assert( iAgg
>=0 && iAgg
<pAggInfo
->nColumn
);
6286 if( pAggInfo
->aCol
[iAgg
].pCExpr
==pExpr
){
6287 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
6289 pAggInfo
->aCol
[iAgg
].pCExpr
= pExpr
;
6290 sqlite3ExprDeferredDelete(pParse
, pExpr
);
6294 assert( pExpr
->op
==TK_AGG_FUNCTION
);
6295 assert( iAgg
>=0 && iAgg
<pAggInfo
->nFunc
);
6296 if( pAggInfo
->aFunc
[iAgg
].pFExpr
==pExpr
){
6297 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
6299 pAggInfo
->aFunc
[iAgg
].pFExpr
= pExpr
;
6300 sqlite3ExprDeferredDelete(pParse
, pExpr
);
6305 return WRC_Continue
;
6309 ** Initialize a Walker object so that will persist AggInfo entries referenced
6310 ** by the tree that is walked.
6312 void sqlite3AggInfoPersistWalkerInit(Walker
*pWalker
, Parse
*pParse
){
6313 memset(pWalker
, 0, sizeof(*pWalker
));
6314 pWalker
->pParse
= pParse
;
6315 pWalker
->xExprCallback
= agginfoPersistExprCb
;
6316 pWalker
->xSelectCallback
= sqlite3SelectWalkNoop
;
6320 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6321 ** the new element. Return a negative number if malloc fails.
6323 static int addAggInfoColumn(sqlite3
*db
, AggInfo
*pInfo
){
6325 pInfo
->aCol
= sqlite3ArrayAllocate(
6328 sizeof(pInfo
->aCol
[0]),
6336 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6337 ** the new element. Return a negative number if malloc fails.
6339 static int addAggInfoFunc(sqlite3
*db
, AggInfo
*pInfo
){
6341 pInfo
->aFunc
= sqlite3ArrayAllocate(
6344 sizeof(pInfo
->aFunc
[0]),
6352 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6353 ** Return the index in aCol[] of the entry that describes that column.
6355 ** If no prior entry is found, create a new one and return -1. The
6356 ** new column will have an idex of pAggInfo->nColumn-1.
6358 static void findOrCreateAggInfoColumn(
6359 Parse
*pParse
, /* Parsing context */
6360 AggInfo
*pAggInfo
, /* The AggInfo object to search and/or modify */
6361 Expr
*pExpr
/* Expr describing the column to find or insert */
6363 struct AggInfo_col
*pCol
;
6366 assert( pAggInfo
->iFirstReg
==0 );
6367 pCol
= pAggInfo
->aCol
;
6368 for(k
=0; k
<pAggInfo
->nColumn
; k
++, pCol
++){
6369 if( pCol
->iTable
==pExpr
->iTable
6370 && pCol
->iColumn
==pExpr
->iColumn
6371 && pExpr
->op
!=TK_IF_NULL_ROW
6376 k
= addAggInfoColumn(pParse
->db
, pAggInfo
);
6379 assert( pParse
->db
->mallocFailed
);
6382 pCol
= &pAggInfo
->aCol
[k
];
6383 assert( ExprUseYTab(pExpr
) );
6384 pCol
->pTab
= pExpr
->y
.pTab
;
6385 pCol
->iTable
= pExpr
->iTable
;
6386 pCol
->iColumn
= pExpr
->iColumn
;
6387 pCol
->iSorterColumn
= -1;
6388 pCol
->pCExpr
= pExpr
;
6389 if( pAggInfo
->pGroupBy
&& pExpr
->op
!=TK_IF_NULL_ROW
){
6391 ExprList
*pGB
= pAggInfo
->pGroupBy
;
6392 struct ExprList_item
*pTerm
= pGB
->a
;
6394 for(j
=0; j
<n
; j
++, pTerm
++){
6395 Expr
*pE
= pTerm
->pExpr
;
6396 if( pE
->op
==TK_COLUMN
6397 && pE
->iTable
==pExpr
->iTable
6398 && pE
->iColumn
==pExpr
->iColumn
6400 pCol
->iSorterColumn
= j
;
6405 if( pCol
->iSorterColumn
<0 ){
6406 pCol
->iSorterColumn
= pAggInfo
->nSortingColumn
++;
6409 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
6410 assert( pExpr
->pAggInfo
==0 || pExpr
->pAggInfo
==pAggInfo
);
6411 pExpr
->pAggInfo
= pAggInfo
;
6412 if( pExpr
->op
==TK_COLUMN
){
6413 pExpr
->op
= TK_AGG_COLUMN
;
6415 pExpr
->iAgg
= (i16
)k
;
6419 ** This is the xExprCallback for a tree walker. It is used to
6420 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
6421 ** for additional information.
6423 static int analyzeAggregate(Walker
*pWalker
, Expr
*pExpr
){
6425 NameContext
*pNC
= pWalker
->u
.pNC
;
6426 Parse
*pParse
= pNC
->pParse
;
6427 SrcList
*pSrcList
= pNC
->pSrcList
;
6428 AggInfo
*pAggInfo
= pNC
->uNC
.pAggInfo
;
6430 assert( pNC
->ncFlags
& NC_UAggInfo
);
6431 assert( pAggInfo
->iFirstReg
==0 );
6432 switch( pExpr
->op
){
6436 assert( pParse
->iSelfTab
==0 );
6437 if( (pNC
->ncFlags
& NC_InAggFunc
)==0 ) break;
6438 if( pParse
->pIdxEpr
==0 ) break;
6439 for(pIEpr
=pParse
->pIdxEpr
; pIEpr
; pIEpr
=pIEpr
->pIENext
){
6440 int iDataCur
= pIEpr
->iDataCur
;
6441 if( iDataCur
<0 ) continue;
6442 if( sqlite3ExprCompare(0, pExpr
, pIEpr
->pExpr
, iDataCur
)==0 ) break;
6444 if( pIEpr
==0 ) break;
6445 if( NEVER(!ExprUseYTab(pExpr
)) ) break;
6446 if( pExpr
->pAggInfo
!=0 ) break; /* Already resolved by outer context */
6448 /* If we reach this point, it means that expression pExpr can be
6449 ** translated into a reference to an index column as described by
6452 memset(&tmp
, 0, sizeof(tmp
));
6453 tmp
.op
= TK_AGG_COLUMN
;
6454 tmp
.iTable
= pIEpr
->iIdxCur
;
6455 tmp
.iColumn
= pIEpr
->iIdxCol
;
6456 findOrCreateAggInfoColumn(pParse
, pAggInfo
, &tmp
);
6457 pAggInfo
->aCol
[tmp
.iAgg
].pCExpr
= pExpr
;
6458 pExpr
->pAggInfo
= pAggInfo
;
6459 pExpr
->iAgg
= tmp
.iAgg
;
6462 case TK_IF_NULL_ROW
:
6465 testcase( pExpr
->op
==TK_AGG_COLUMN
);
6466 testcase( pExpr
->op
==TK_COLUMN
);
6467 testcase( pExpr
->op
==TK_IF_NULL_ROW
);
6468 /* Check to see if the column is in one of the tables in the FROM
6469 ** clause of the aggregate query */
6470 if( ALWAYS(pSrcList
!=0) ){
6471 SrcItem
*pItem
= pSrcList
->a
;
6472 for(i
=0; i
<pSrcList
->nSrc
; i
++, pItem
++){
6473 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
6474 if( pExpr
->iTable
==pItem
->iCursor
){
6475 findOrCreateAggInfoColumn(pParse
, pAggInfo
, pExpr
);
6477 } /* endif pExpr->iTable==pItem->iCursor */
6478 } /* end loop over pSrcList */
6482 case TK_AGG_FUNCTION
: {
6483 if( (pNC
->ncFlags
& NC_InAggFunc
)==0
6484 && pWalker
->walkerDepth
==pExpr
->op2
6486 /* Check to see if pExpr is a duplicate of another aggregate
6487 ** function that is already in the pAggInfo structure
6489 struct AggInfo_func
*pItem
= pAggInfo
->aFunc
;
6490 for(i
=0; i
<pAggInfo
->nFunc
; i
++, pItem
++){
6491 if( pItem
->pFExpr
==pExpr
) break;
6492 if( sqlite3ExprCompare(0, pItem
->pFExpr
, pExpr
, -1)==0 ){
6496 if( i
>=pAggInfo
->nFunc
){
6497 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
6499 u8 enc
= ENC(pParse
->db
);
6500 i
= addAggInfoFunc(pParse
->db
, pAggInfo
);
6502 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
6503 pItem
= &pAggInfo
->aFunc
[i
];
6504 pItem
->pFExpr
= pExpr
;
6505 assert( ExprUseUToken(pExpr
) );
6506 pItem
->pFunc
= sqlite3FindFunction(pParse
->db
,
6508 pExpr
->x
.pList
? pExpr
->x
.pList
->nExpr
: 0, enc
, 0);
6509 if( pExpr
->flags
& EP_Distinct
){
6510 pItem
->iDistinct
= pParse
->nTab
++;
6512 pItem
->iDistinct
= -1;
6516 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6518 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
6519 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
6520 pExpr
->iAgg
= (i16
)i
;
6521 pExpr
->pAggInfo
= pAggInfo
;
6524 return WRC_Continue
;
6528 return WRC_Continue
;
6532 ** Analyze the pExpr expression looking for aggregate functions and
6533 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6534 ** points to. Additional entries are made on the AggInfo object as
6537 ** This routine should only be called after the expression has been
6538 ** analyzed by sqlite3ResolveExprNames().
6540 void sqlite3ExprAnalyzeAggregates(NameContext
*pNC
, Expr
*pExpr
){
6542 w
.xExprCallback
= analyzeAggregate
;
6543 w
.xSelectCallback
= sqlite3WalkerDepthIncrease
;
6544 w
.xSelectCallback2
= sqlite3WalkerDepthDecrease
;
6548 assert( pNC
->pSrcList
!=0 );
6549 sqlite3WalkExpr(&w
, pExpr
);
6553 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
6554 ** expression list. Return the number of errors.
6556 ** If an error is found, the analysis is cut short.
6558 void sqlite3ExprAnalyzeAggList(NameContext
*pNC
, ExprList
*pList
){
6559 struct ExprList_item
*pItem
;
6562 for(pItem
=pList
->a
, i
=0; i
<pList
->nExpr
; i
++, pItem
++){
6563 sqlite3ExprAnalyzeAggregates(pNC
, pItem
->pExpr
);
6569 ** Allocate a single new register for use to hold some intermediate result.
6571 int sqlite3GetTempReg(Parse
*pParse
){
6572 if( pParse
->nTempReg
==0 ){
6573 return ++pParse
->nMem
;
6575 return pParse
->aTempReg
[--pParse
->nTempReg
];
6579 ** Deallocate a register, making available for reuse for some other
6582 void sqlite3ReleaseTempReg(Parse
*pParse
, int iReg
){
6584 sqlite3VdbeReleaseRegisters(pParse
, iReg
, 1, 0, 0);
6585 if( pParse
->nTempReg
<ArraySize(pParse
->aTempReg
) ){
6586 pParse
->aTempReg
[pParse
->nTempReg
++] = iReg
;
6592 ** Allocate or deallocate a block of nReg consecutive registers.
6594 int sqlite3GetTempRange(Parse
*pParse
, int nReg
){
6596 if( nReg
==1 ) return sqlite3GetTempReg(pParse
);
6597 i
= pParse
->iRangeReg
;
6598 n
= pParse
->nRangeReg
;
6600 pParse
->iRangeReg
+= nReg
;
6601 pParse
->nRangeReg
-= nReg
;
6604 pParse
->nMem
+= nReg
;
6608 void sqlite3ReleaseTempRange(Parse
*pParse
, int iReg
, int nReg
){
6610 sqlite3ReleaseTempReg(pParse
, iReg
);
6613 sqlite3VdbeReleaseRegisters(pParse
, iReg
, nReg
, 0, 0);
6614 if( nReg
>pParse
->nRangeReg
){
6615 pParse
->nRangeReg
= nReg
;
6616 pParse
->iRangeReg
= iReg
;
6621 ** Mark all temporary registers as being unavailable for reuse.
6623 ** Always invoke this procedure after coding a subroutine or co-routine
6624 ** that might be invoked from other parts of the code, to ensure that
6625 ** the sub/co-routine does not use registers in common with the code that
6626 ** invokes the sub/co-routine.
6628 void sqlite3ClearTempRegCache(Parse
*pParse
){
6629 pParse
->nTempReg
= 0;
6630 pParse
->nRangeReg
= 0;
6634 ** Validate that no temporary register falls within the range of
6635 ** iFirst..iLast, inclusive. This routine is only call from within assert()
6639 int sqlite3NoTempsInRange(Parse
*pParse
, int iFirst
, int iLast
){
6641 if( pParse
->nRangeReg
>0
6642 && pParse
->iRangeReg
+pParse
->nRangeReg
> iFirst
6643 && pParse
->iRangeReg
<= iLast
6647 for(i
=0; i
<pParse
->nTempReg
; i
++){
6648 if( pParse
->aTempReg
[i
]>=iFirst
&& pParse
->aTempReg
[i
]<=iLast
){
6654 #endif /* SQLITE_DEBUG */