4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
15 #include "sqliteInt.h"
17 /* Forward declarations */
18 static void exprCodeBetween(Parse
*,Expr
*,int,void(*)(Parse
*,Expr
*,int,int),int);
19 static int exprCodeVector(Parse
*pParse
, Expr
*p
, int *piToFree
);
22 ** Return the affinity character for a single column of a table.
24 char sqlite3TableColumnAffinity(const Table
*pTab
, int iCol
){
25 if( iCol
<0 || NEVER(iCol
>=pTab
->nCol
) ) return SQLITE_AFF_INTEGER
;
26 return pTab
->aCol
[iCol
].affinity
;
30 ** Return the 'affinity' of the expression pExpr if any.
32 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33 ** or a sub-select with a column as the return value, then the
34 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35 ** indicating no affinity for the expression.
37 ** i.e. the WHERE clause expressions in the following statements all
40 ** CREATE TABLE t1(a);
41 ** SELECT * FROM t1 WHERE a;
42 ** SELECT a AS b FROM t1 WHERE b;
43 ** SELECT * FROM t1 WHERE (select a from t1);
45 char sqlite3ExprAffinity(const Expr
*pExpr
){
48 while( 1 /* exit-by-break */ ){
49 if( op
==TK_COLUMN
|| (op
==TK_AGG_COLUMN
&& pExpr
->y
.pTab
!=0) ){
50 assert( ExprUseYTab(pExpr
) );
51 assert( pExpr
->y
.pTab
!=0 );
52 return sqlite3TableColumnAffinity(pExpr
->y
.pTab
, pExpr
->iColumn
);
55 assert( ExprUseXSelect(pExpr
) );
56 assert( pExpr
->x
.pSelect
!=0 );
57 assert( pExpr
->x
.pSelect
->pEList
!=0 );
58 assert( pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
!=0 );
59 return sqlite3ExprAffinity(pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
);
61 #ifndef SQLITE_OMIT_CAST
63 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
64 return sqlite3AffinityType(pExpr
->u
.zToken
, 0);
67 if( op
==TK_SELECT_COLUMN
){
68 assert( pExpr
->pLeft
!=0 && ExprUseXSelect(pExpr
->pLeft
) );
69 assert( pExpr
->iColumn
< pExpr
->iTable
);
70 assert( pExpr
->iColumn
>= 0 );
71 assert( pExpr
->iTable
==pExpr
->pLeft
->x
.pSelect
->pEList
->nExpr
);
72 return sqlite3ExprAffinity(
73 pExpr
->pLeft
->x
.pSelect
->pEList
->a
[pExpr
->iColumn
].pExpr
77 assert( ExprUseXList(pExpr
) );
78 return sqlite3ExprAffinity(pExpr
->x
.pList
->a
[0].pExpr
);
80 if( ExprHasProperty(pExpr
, EP_Skip
|EP_IfNullRow
) ){
81 assert( pExpr
->op
==TK_COLLATE
82 || pExpr
->op
==TK_IF_NULL_ROW
83 || (pExpr
->op
==TK_REGISTER
&& pExpr
->op2
==TK_IF_NULL_ROW
) );
88 if( op
!=TK_REGISTER
|| (op
= pExpr
->op2
)==TK_REGISTER
) break;
90 return pExpr
->affExpr
;
94 ** Make a guess at all the possible datatypes of the result that could
95 ** be returned by an expression. Return a bitmask indicating the answer:
101 ** If the expression must return NULL, then 0x00 is returned.
103 int sqlite3ExprDataType(const Expr
*pExpr
){
109 pExpr
= pExpr
->pLeft
;
126 case TK_AGG_FUNCTION
:
134 case TK_SELECT_COLUMN
:
136 int aff
= sqlite3ExprAffinity(pExpr
);
137 if( aff
>=SQLITE_AFF_NUMERIC
) return 0x05;
138 if( aff
==SQLITE_AFF_TEXT
) return 0x06;
144 ExprList
*pList
= pExpr
->x
.pList
;
145 assert( ExprUseXList(pExpr
) && pList
!=0 );
146 assert( pList
->nExpr
> 0);
147 for(ii
=1; ii
<pList
->nExpr
; ii
+=2){
148 res
|= sqlite3ExprDataType(pList
->a
[ii
].pExpr
);
150 if( pList
->nExpr
% 2 ){
151 res
|= sqlite3ExprDataType(pList
->a
[pList
->nExpr
-1].pExpr
);
158 } /* End of switch(op) */
159 } /* End of while(pExpr) */
164 ** Set the collating sequence for expression pExpr to be the collating
165 ** sequence named by pToken. Return a pointer to a new Expr node that
166 ** implements the COLLATE operator.
168 ** If a memory allocation error occurs, that fact is recorded in pParse->db
169 ** and the pExpr parameter is returned unchanged.
171 Expr
*sqlite3ExprAddCollateToken(
172 const Parse
*pParse
, /* Parsing context */
173 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
174 const Token
*pCollName
, /* Name of collating sequence */
175 int dequote
/* True to dequote pCollName */
177 if( pCollName
->n
>0 ){
178 Expr
*pNew
= sqlite3ExprAlloc(pParse
->db
, TK_COLLATE
, pCollName
, dequote
);
181 pNew
->flags
|= EP_Collate
|EP_Skip
;
187 Expr
*sqlite3ExprAddCollateString(
188 const Parse
*pParse
, /* Parsing context */
189 Expr
*pExpr
, /* Add the "COLLATE" clause to this expression */
190 const char *zC
/* The collating sequence name */
194 sqlite3TokenInit(&s
, (char*)zC
);
195 return sqlite3ExprAddCollateToken(pParse
, pExpr
, &s
, 0);
199 ** Skip over any TK_COLLATE operators.
201 Expr
*sqlite3ExprSkipCollate(Expr
*pExpr
){
202 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
) ){
203 assert( pExpr
->op
==TK_COLLATE
);
204 pExpr
= pExpr
->pLeft
;
210 ** Skip over any TK_COLLATE operators and/or any unlikely()
211 ** or likelihood() or likely() functions at the root of an
214 Expr
*sqlite3ExprSkipCollateAndLikely(Expr
*pExpr
){
215 while( pExpr
&& ExprHasProperty(pExpr
, EP_Skip
|EP_Unlikely
) ){
216 if( ExprHasProperty(pExpr
, EP_Unlikely
) ){
217 assert( ExprUseXList(pExpr
) );
218 assert( pExpr
->x
.pList
->nExpr
>0 );
219 assert( pExpr
->op
==TK_FUNCTION
);
220 pExpr
= pExpr
->x
.pList
->a
[0].pExpr
;
222 assert( pExpr
->op
==TK_COLLATE
);
223 pExpr
= pExpr
->pLeft
;
230 ** Return the collation sequence for the expression pExpr. If
231 ** there is no defined collating sequence, return NULL.
233 ** See also: sqlite3ExprNNCollSeq()
235 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
236 ** default collation if pExpr has no defined collation.
238 ** The collating sequence might be determined by a COLLATE operator
239 ** or by the presence of a column with a defined collating sequence.
240 ** COLLATE operators take first precedence. Left operands take
241 ** precedence over right operands.
243 CollSeq
*sqlite3ExprCollSeq(Parse
*pParse
, const Expr
*pExpr
){
244 sqlite3
*db
= pParse
->db
;
246 const Expr
*p
= pExpr
;
249 if( op
==TK_REGISTER
) op
= p
->op2
;
250 if( (op
==TK_AGG_COLUMN
&& p
->y
.pTab
!=0)
251 || op
==TK_COLUMN
|| op
==TK_TRIGGER
254 assert( ExprUseYTab(p
) );
255 assert( p
->y
.pTab
!=0 );
256 if( (j
= p
->iColumn
)>=0 ){
257 const char *zColl
= sqlite3ColumnColl(&p
->y
.pTab
->aCol
[j
]);
258 pColl
= sqlite3FindCollSeq(db
, ENC(db
), zColl
, 0);
262 if( op
==TK_CAST
|| op
==TK_UPLUS
){
267 assert( ExprUseXList(p
) );
268 p
= p
->x
.pList
->a
[0].pExpr
;
271 if( op
==TK_COLLATE
){
272 assert( !ExprHasProperty(p
, EP_IntValue
) );
273 pColl
= sqlite3GetCollSeq(pParse
, ENC(db
), 0, p
->u
.zToken
);
276 if( p
->flags
& EP_Collate
){
277 if( p
->pLeft
&& (p
->pLeft
->flags
& EP_Collate
)!=0 ){
280 Expr
*pNext
= p
->pRight
;
281 /* The Expr.x union is never used at the same time as Expr.pRight */
282 assert( !ExprUseXList(p
) || p
->x
.pList
==0 || p
->pRight
==0 );
283 if( ExprUseXList(p
) && p
->x
.pList
!=0 && !db
->mallocFailed
){
285 for(i
=0; i
<p
->x
.pList
->nExpr
; i
++){
286 if( ExprHasProperty(p
->x
.pList
->a
[i
].pExpr
, EP_Collate
) ){
287 pNext
= p
->x
.pList
->a
[i
].pExpr
;
298 if( sqlite3CheckCollSeq(pParse
, pColl
) ){
305 ** Return the collation sequence for the expression pExpr. If
306 ** there is no defined collating sequence, return a pointer to the
307 ** default collation sequence.
309 ** See also: sqlite3ExprCollSeq()
311 ** The sqlite3ExprCollSeq() routine works the same except that it
312 ** returns NULL if there is no defined collation.
314 CollSeq
*sqlite3ExprNNCollSeq(Parse
*pParse
, const Expr
*pExpr
){
315 CollSeq
*p
= sqlite3ExprCollSeq(pParse
, pExpr
);
316 if( p
==0 ) p
= pParse
->db
->pDfltColl
;
322 ** Return TRUE if the two expressions have equivalent collating sequences.
324 int sqlite3ExprCollSeqMatch(Parse
*pParse
, const Expr
*pE1
, const Expr
*pE2
){
325 CollSeq
*pColl1
= sqlite3ExprNNCollSeq(pParse
, pE1
);
326 CollSeq
*pColl2
= sqlite3ExprNNCollSeq(pParse
, pE2
);
327 return sqlite3StrICmp(pColl1
->zName
, pColl2
->zName
)==0;
331 ** pExpr is an operand of a comparison operator. aff2 is the
332 ** type affinity of the other operand. This routine returns the
333 ** type affinity that should be used for the comparison operator.
335 char sqlite3CompareAffinity(const Expr
*pExpr
, char aff2
){
336 char aff1
= sqlite3ExprAffinity(pExpr
);
337 if( aff1
>SQLITE_AFF_NONE
&& aff2
>SQLITE_AFF_NONE
){
338 /* Both sides of the comparison are columns. If one has numeric
339 ** affinity, use that. Otherwise use no affinity.
341 if( sqlite3IsNumericAffinity(aff1
) || sqlite3IsNumericAffinity(aff2
) ){
342 return SQLITE_AFF_NUMERIC
;
344 return SQLITE_AFF_BLOB
;
347 /* One side is a column, the other is not. Use the columns affinity. */
348 assert( aff1
<=SQLITE_AFF_NONE
|| aff2
<=SQLITE_AFF_NONE
);
349 return (aff1
<=SQLITE_AFF_NONE
? aff2
: aff1
) | SQLITE_AFF_NONE
;
354 ** pExpr is a comparison operator. Return the type affinity that should
355 ** be applied to both operands prior to doing the comparison.
357 static char comparisonAffinity(const Expr
*pExpr
){
359 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_IN
|| pExpr
->op
==TK_LT
||
360 pExpr
->op
==TK_GT
|| pExpr
->op
==TK_GE
|| pExpr
->op
==TK_LE
||
361 pExpr
->op
==TK_NE
|| pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
);
362 assert( pExpr
->pLeft
);
363 aff
= sqlite3ExprAffinity(pExpr
->pLeft
);
365 aff
= sqlite3CompareAffinity(pExpr
->pRight
, aff
);
366 }else if( ExprUseXSelect(pExpr
) ){
367 aff
= sqlite3CompareAffinity(pExpr
->x
.pSelect
->pEList
->a
[0].pExpr
, aff
);
369 aff
= SQLITE_AFF_BLOB
;
375 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
376 ** idx_affinity is the affinity of an indexed column. Return true
377 ** if the index with affinity idx_affinity may be used to implement
378 ** the comparison in pExpr.
380 int sqlite3IndexAffinityOk(const Expr
*pExpr
, char idx_affinity
){
381 char aff
= comparisonAffinity(pExpr
);
382 if( aff
<SQLITE_AFF_TEXT
){
385 if( aff
==SQLITE_AFF_TEXT
){
386 return idx_affinity
==SQLITE_AFF_TEXT
;
388 return sqlite3IsNumericAffinity(idx_affinity
);
392 ** Return the P5 value that should be used for a binary comparison
393 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
395 static u8
binaryCompareP5(
396 const Expr
*pExpr1
, /* Left operand */
397 const Expr
*pExpr2
, /* Right operand */
398 int jumpIfNull
/* Extra flags added to P5 */
400 u8 aff
= (char)sqlite3ExprAffinity(pExpr2
);
401 aff
= (u8
)sqlite3CompareAffinity(pExpr1
, aff
) | (u8
)jumpIfNull
;
406 ** Return a pointer to the collation sequence that should be used by
407 ** a binary comparison operator comparing pLeft and pRight.
409 ** If the left hand expression has a collating sequence type, then it is
410 ** used. Otherwise the collation sequence for the right hand expression
411 ** is used, or the default (BINARY) if neither expression has a collating
414 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
415 ** it is not considered.
417 CollSeq
*sqlite3BinaryCompareCollSeq(
424 if( pLeft
->flags
& EP_Collate
){
425 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
426 }else if( pRight
&& (pRight
->flags
& EP_Collate
)!=0 ){
427 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
429 pColl
= sqlite3ExprCollSeq(pParse
, pLeft
);
431 pColl
= sqlite3ExprCollSeq(pParse
, pRight
);
437 /* Expression p is a comparison operator. Return a collation sequence
438 ** appropriate for the comparison operator.
440 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
441 ** However, if the OP_Commuted flag is set, then the order of the operands
442 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
443 ** correct collating sequence is found.
445 CollSeq
*sqlite3ExprCompareCollSeq(Parse
*pParse
, const Expr
*p
){
446 if( ExprHasProperty(p
, EP_Commuted
) ){
447 return sqlite3BinaryCompareCollSeq(pParse
, p
->pRight
, p
->pLeft
);
449 return sqlite3BinaryCompareCollSeq(pParse
, p
->pLeft
, p
->pRight
);
454 ** Generate code for a comparison operator.
456 static int codeCompare(
457 Parse
*pParse
, /* The parsing (and code generating) context */
458 Expr
*pLeft
, /* The left operand */
459 Expr
*pRight
, /* The right operand */
460 int opcode
, /* The comparison opcode */
461 int in1
, int in2
, /* Register holding operands */
462 int dest
, /* Jump here if true. */
463 int jumpIfNull
, /* If true, jump if either operand is NULL */
464 int isCommuted
/* The comparison has been commuted */
470 if( pParse
->nErr
) return 0;
472 p4
= sqlite3BinaryCompareCollSeq(pParse
, pRight
, pLeft
);
474 p4
= sqlite3BinaryCompareCollSeq(pParse
, pLeft
, pRight
);
476 p5
= binaryCompareP5(pLeft
, pRight
, jumpIfNull
);
477 addr
= sqlite3VdbeAddOp4(pParse
->pVdbe
, opcode
, in2
, dest
, in1
,
478 (void*)p4
, P4_COLLSEQ
);
479 sqlite3VdbeChangeP5(pParse
->pVdbe
, (u8
)p5
);
484 ** Return true if expression pExpr is a vector, or false otherwise.
486 ** A vector is defined as any expression that results in two or more
487 ** columns of result. Every TK_VECTOR node is an vector because the
488 ** parser will not generate a TK_VECTOR with fewer than two entries.
489 ** But a TK_SELECT might be either a vector or a scalar. It is only
490 ** considered a vector if it has two or more result columns.
492 int sqlite3ExprIsVector(const Expr
*pExpr
){
493 return sqlite3ExprVectorSize(pExpr
)>1;
497 ** If the expression passed as the only argument is of type TK_VECTOR
498 ** return the number of expressions in the vector. Or, if the expression
499 ** is a sub-select, return the number of columns in the sub-select. For
500 ** any other type of expression, return 1.
502 int sqlite3ExprVectorSize(const Expr
*pExpr
){
504 if( op
==TK_REGISTER
) op
= pExpr
->op2
;
506 assert( ExprUseXList(pExpr
) );
507 return pExpr
->x
.pList
->nExpr
;
508 }else if( op
==TK_SELECT
){
509 assert( ExprUseXSelect(pExpr
) );
510 return pExpr
->x
.pSelect
->pEList
->nExpr
;
517 ** Return a pointer to a subexpression of pVector that is the i-th
518 ** column of the vector (numbered starting with 0). The caller must
519 ** ensure that i is within range.
521 ** If pVector is really a scalar (and "scalar" here includes subqueries
522 ** that return a single column!) then return pVector unmodified.
524 ** pVector retains ownership of the returned subexpression.
526 ** If the vector is a (SELECT ...) then the expression returned is
527 ** just the expression for the i-th term of the result set, and may
528 ** not be ready for evaluation because the table cursor has not yet
531 Expr
*sqlite3VectorFieldSubexpr(Expr
*pVector
, int i
){
532 assert( i
<sqlite3ExprVectorSize(pVector
) || pVector
->op
==TK_ERROR
);
533 if( sqlite3ExprIsVector(pVector
) ){
534 assert( pVector
->op2
==0 || pVector
->op
==TK_REGISTER
);
535 if( pVector
->op
==TK_SELECT
|| pVector
->op2
==TK_SELECT
){
536 assert( ExprUseXSelect(pVector
) );
537 return pVector
->x
.pSelect
->pEList
->a
[i
].pExpr
;
539 assert( ExprUseXList(pVector
) );
540 return pVector
->x
.pList
->a
[i
].pExpr
;
547 ** Compute and return a new Expr object which when passed to
548 ** sqlite3ExprCode() will generate all necessary code to compute
549 ** the iField-th column of the vector expression pVector.
551 ** It is ok for pVector to be a scalar (as long as iField==0).
552 ** In that case, this routine works like sqlite3ExprDup().
554 ** The caller owns the returned Expr object and is responsible for
555 ** ensuring that the returned value eventually gets freed.
557 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
558 ** then the returned object will reference pVector and so pVector must remain
559 ** valid for the life of the returned object. If pVector is a TK_VECTOR
560 ** or a scalar expression, then it can be deleted as soon as this routine
563 ** A trick to cause a TK_SELECT pVector to be deleted together with
564 ** the returned Expr object is to attach the pVector to the pRight field
565 ** of the returned TK_SELECT_COLUMN Expr object.
567 Expr
*sqlite3ExprForVectorField(
568 Parse
*pParse
, /* Parsing context */
569 Expr
*pVector
, /* The vector. List of expressions or a sub-SELECT */
570 int iField
, /* Which column of the vector to return */
571 int nField
/* Total number of columns in the vector */
574 if( pVector
->op
==TK_SELECT
){
575 assert( ExprUseXSelect(pVector
) );
576 /* The TK_SELECT_COLUMN Expr node:
578 ** pLeft: pVector containing TK_SELECT. Not deleted.
579 ** pRight: not used. But recursively deleted.
580 ** iColumn: Index of a column in pVector
581 ** iTable: 0 or the number of columns on the LHS of an assignment
582 ** pLeft->iTable: First in an array of register holding result, or 0
583 ** if the result is not yet computed.
585 ** sqlite3ExprDelete() specifically skips the recursive delete of
586 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
587 ** can be attached to pRight to cause this node to take ownership of
588 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
589 ** with the same pLeft pointer to the pVector, but only one of them
590 ** will own the pVector.
592 pRet
= sqlite3PExpr(pParse
, TK_SELECT_COLUMN
, 0, 0);
594 ExprSetProperty(pRet
, EP_FullSize
);
595 pRet
->iTable
= nField
;
596 pRet
->iColumn
= iField
;
597 pRet
->pLeft
= pVector
;
600 if( pVector
->op
==TK_VECTOR
){
602 assert( ExprUseXList(pVector
) );
603 ppVector
= &pVector
->x
.pList
->a
[iField
].pExpr
;
605 if( IN_RENAME_OBJECT
){
606 /* This must be a vector UPDATE inside a trigger */
611 pRet
= sqlite3ExprDup(pParse
->db
, pVector
, 0);
617 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
618 ** it. Return the register in which the result is stored (or, if the
619 ** sub-select returns more than one column, the first in an array
620 ** of registers in which the result is stored).
622 ** If pExpr is not a TK_SELECT expression, return 0.
624 static int exprCodeSubselect(Parse
*pParse
, Expr
*pExpr
){
626 #ifndef SQLITE_OMIT_SUBQUERY
627 if( pExpr
->op
==TK_SELECT
){
628 reg
= sqlite3CodeSubselect(pParse
, pExpr
);
635 ** Argument pVector points to a vector expression - either a TK_VECTOR
636 ** or TK_SELECT that returns more than one column. This function returns
637 ** the register number of a register that contains the value of
638 ** element iField of the vector.
640 ** If pVector is a TK_SELECT expression, then code for it must have
641 ** already been generated using the exprCodeSubselect() routine. In this
642 ** case parameter regSelect should be the first in an array of registers
643 ** containing the results of the sub-select.
645 ** If pVector is of type TK_VECTOR, then code for the requested field
646 ** is generated. In this case (*pRegFree) may be set to the number of
647 ** a temporary register to be freed by the caller before returning.
649 ** Before returning, output parameter (*ppExpr) is set to point to the
650 ** Expr object corresponding to element iElem of the vector.
652 static int exprVectorRegister(
653 Parse
*pParse
, /* Parse context */
654 Expr
*pVector
, /* Vector to extract element from */
655 int iField
, /* Field to extract from pVector */
656 int regSelect
, /* First in array of registers */
657 Expr
**ppExpr
, /* OUT: Expression element */
658 int *pRegFree
/* OUT: Temp register to free */
661 assert( op
==TK_VECTOR
|| op
==TK_REGISTER
|| op
==TK_SELECT
|| op
==TK_ERROR
);
662 if( op
==TK_REGISTER
){
663 *ppExpr
= sqlite3VectorFieldSubexpr(pVector
, iField
);
664 return pVector
->iTable
+iField
;
667 assert( ExprUseXSelect(pVector
) );
668 *ppExpr
= pVector
->x
.pSelect
->pEList
->a
[iField
].pExpr
;
669 return regSelect
+iField
;
672 assert( ExprUseXList(pVector
) );
673 *ppExpr
= pVector
->x
.pList
->a
[iField
].pExpr
;
674 return sqlite3ExprCodeTemp(pParse
, *ppExpr
, pRegFree
);
680 ** Expression pExpr is a comparison between two vector values. Compute
681 ** the result of the comparison (1, 0, or NULL) and write that
682 ** result into register dest.
684 ** The caller must satisfy the following preconditions:
686 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
687 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
688 ** otherwise: op==pExpr->op and p5==0
690 static void codeVectorCompare(
691 Parse
*pParse
, /* Code generator context */
692 Expr
*pExpr
, /* The comparison operation */
693 int dest
, /* Write results into this register */
694 u8 op
, /* Comparison operator */
695 u8 p5
/* SQLITE_NULLEQ or zero */
697 Vdbe
*v
= pParse
->pVdbe
;
698 Expr
*pLeft
= pExpr
->pLeft
;
699 Expr
*pRight
= pExpr
->pRight
;
700 int nLeft
= sqlite3ExprVectorSize(pLeft
);
706 int addrDone
= sqlite3VdbeMakeLabel(pParse
);
707 int isCommuted
= ExprHasProperty(pExpr
,EP_Commuted
);
709 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
710 if( pParse
->nErr
) return;
711 if( nLeft
!=sqlite3ExprVectorSize(pRight
) ){
712 sqlite3ErrorMsg(pParse
, "row value misused");
715 assert( pExpr
->op
==TK_EQ
|| pExpr
->op
==TK_NE
716 || pExpr
->op
==TK_IS
|| pExpr
->op
==TK_ISNOT
717 || pExpr
->op
==TK_LT
|| pExpr
->op
==TK_GT
718 || pExpr
->op
==TK_LE
|| pExpr
->op
==TK_GE
720 assert( pExpr
->op
==op
|| (pExpr
->op
==TK_IS
&& op
==TK_EQ
)
721 || (pExpr
->op
==TK_ISNOT
&& op
==TK_NE
) );
722 assert( p5
==0 || pExpr
->op
!=op
);
723 assert( p5
==SQLITE_NULLEQ
|| pExpr
->op
==op
);
725 if( op
==TK_LE
) opx
= TK_LT
;
726 if( op
==TK_GE
) opx
= TK_GT
;
727 if( op
==TK_NE
) opx
= TK_EQ
;
729 regLeft
= exprCodeSubselect(pParse
, pLeft
);
730 regRight
= exprCodeSubselect(pParse
, pRight
);
732 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, dest
);
733 for(i
=0; 1 /*Loop exits by "break"*/; i
++){
734 int regFree1
= 0, regFree2
= 0;
735 Expr
*pL
= 0, *pR
= 0;
737 assert( i
>=0 && i
<nLeft
);
738 if( addrCmp
) sqlite3VdbeJumpHere(v
, addrCmp
);
739 r1
= exprVectorRegister(pParse
, pLeft
, i
, regLeft
, &pL
, ®Free1
);
740 r2
= exprVectorRegister(pParse
, pRight
, i
, regRight
, &pR
, ®Free2
);
741 addrCmp
= sqlite3VdbeCurrentAddr(v
);
742 codeCompare(pParse
, pL
, pR
, opx
, r1
, r2
, addrDone
, p5
, isCommuted
);
743 testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
744 testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
745 testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
746 testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
747 testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
748 testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
749 sqlite3ReleaseTempReg(pParse
, regFree1
);
750 sqlite3ReleaseTempReg(pParse
, regFree2
);
751 if( (opx
==TK_LT
|| opx
==TK_GT
) && i
<nLeft
-1 ){
752 addrCmp
= sqlite3VdbeAddOp0(v
, OP_ElseEq
);
753 testcase(opx
==TK_LT
); VdbeCoverageIf(v
,opx
==TK_LT
);
754 testcase(opx
==TK_GT
); VdbeCoverageIf(v
,opx
==TK_GT
);
756 if( p5
==SQLITE_NULLEQ
){
757 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
);
759 sqlite3VdbeAddOp3(v
, OP_ZeroOrNull
, r1
, dest
, r2
);
765 sqlite3VdbeAddOp2(v
, OP_NotNull
, dest
, addrDone
); VdbeCoverage(v
);
767 assert( op
==TK_LT
|| op
==TK_GT
|| op
==TK_LE
|| op
==TK_GE
);
768 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, addrDone
);
769 if( i
==nLeft
-2 ) opx
= op
;
772 sqlite3VdbeJumpHere(v
, addrCmp
);
773 sqlite3VdbeResolveLabel(v
, addrDone
);
775 sqlite3VdbeAddOp2(v
, OP_Not
, dest
, dest
);
779 #if SQLITE_MAX_EXPR_DEPTH>0
781 ** Check that argument nHeight is less than or equal to the maximum
782 ** expression depth allowed. If it is not, leave an error message in
785 int sqlite3ExprCheckHeight(Parse
*pParse
, int nHeight
){
787 int mxHeight
= pParse
->db
->aLimit
[SQLITE_LIMIT_EXPR_DEPTH
];
788 if( nHeight
>mxHeight
){
789 sqlite3ErrorMsg(pParse
,
790 "Expression tree is too large (maximum depth %d)", mxHeight
797 /* The following three functions, heightOfExpr(), heightOfExprList()
798 ** and heightOfSelect(), are used to determine the maximum height
799 ** of any expression tree referenced by the structure passed as the
802 ** If this maximum height is greater than the current value pointed
803 ** to by pnHeight, the second parameter, then set *pnHeight to that
806 static void heightOfExpr(const Expr
*p
, int *pnHeight
){
808 if( p
->nHeight
>*pnHeight
){
809 *pnHeight
= p
->nHeight
;
813 static void heightOfExprList(const ExprList
*p
, int *pnHeight
){
816 for(i
=0; i
<p
->nExpr
; i
++){
817 heightOfExpr(p
->a
[i
].pExpr
, pnHeight
);
821 static void heightOfSelect(const Select
*pSelect
, int *pnHeight
){
823 for(p
=pSelect
; p
; p
=p
->pPrior
){
824 heightOfExpr(p
->pWhere
, pnHeight
);
825 heightOfExpr(p
->pHaving
, pnHeight
);
826 heightOfExpr(p
->pLimit
, pnHeight
);
827 heightOfExprList(p
->pEList
, pnHeight
);
828 heightOfExprList(p
->pGroupBy
, pnHeight
);
829 heightOfExprList(p
->pOrderBy
, pnHeight
);
834 ** Set the Expr.nHeight variable in the structure passed as an
835 ** argument. An expression with no children, Expr.pList or
836 ** Expr.pSelect member has a height of 1. Any other expression
837 ** has a height equal to the maximum height of any other
838 ** referenced Expr plus one.
840 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
843 static void exprSetHeight(Expr
*p
){
844 int nHeight
= p
->pLeft
? p
->pLeft
->nHeight
: 0;
845 if( NEVER(p
->pRight
) && p
->pRight
->nHeight
>nHeight
){
846 nHeight
= p
->pRight
->nHeight
;
848 if( ExprUseXSelect(p
) ){
849 heightOfSelect(p
->x
.pSelect
, &nHeight
);
850 }else if( p
->x
.pList
){
851 heightOfExprList(p
->x
.pList
, &nHeight
);
852 p
->flags
|= EP_Propagate
& sqlite3ExprListFlags(p
->x
.pList
);
854 p
->nHeight
= nHeight
+ 1;
858 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
859 ** the height is greater than the maximum allowed expression depth,
860 ** leave an error in pParse.
862 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
865 void sqlite3ExprSetHeightAndFlags(Parse
*pParse
, Expr
*p
){
866 if( pParse
->nErr
) return;
868 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
872 ** Return the maximum height of any expression tree referenced
873 ** by the select statement passed as an argument.
875 int sqlite3SelectExprHeight(const Select
*p
){
877 heightOfSelect(p
, &nHeight
);
880 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
882 ** Propagate all EP_Propagate flags from the Expr.x.pList into
885 void sqlite3ExprSetHeightAndFlags(Parse
*pParse
, Expr
*p
){
886 if( pParse
->nErr
) return;
887 if( p
&& ExprUseXList(p
) && p
->x
.pList
){
888 p
->flags
|= EP_Propagate
& sqlite3ExprListFlags(p
->x
.pList
);
891 #define exprSetHeight(y)
892 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
895 ** Set the error offset for an Expr node, if possible.
897 void sqlite3ExprSetErrorOffset(Expr
*pExpr
, int iOfst
){
898 if( pExpr
==0 ) return;
899 if( NEVER(ExprUseWJoin(pExpr
)) ) return;
900 pExpr
->w
.iOfst
= iOfst
;
904 ** This routine is the core allocator for Expr nodes.
906 ** Construct a new expression node and return a pointer to it. Memory
907 ** for this node and for the pToken argument is a single allocation
908 ** obtained from sqlite3DbMalloc(). The calling function
909 ** is responsible for making sure the node eventually gets freed.
911 ** If dequote is true, then the token (if it exists) is dequoted.
912 ** If dequote is false, no dequoting is performed. The deQuote
913 ** parameter is ignored if pToken is NULL or if the token does not
914 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
915 ** then the EP_DblQuoted flag is set on the expression node.
917 ** Special case: If op==TK_INTEGER and pToken points to a string that
918 ** can be translated into a 32-bit integer, then the token is not
919 ** stored in u.zToken. Instead, the integer values is written
920 ** into u.iValue and the EP_IntValue flag is set. No extra storage
921 ** is allocated to hold the integer text and the dequote flag is ignored.
923 Expr
*sqlite3ExprAlloc(
924 sqlite3
*db
, /* Handle for sqlite3DbMallocRawNN() */
925 int op
, /* Expression opcode */
926 const Token
*pToken
, /* Token argument. Might be NULL */
927 int dequote
/* True to dequote */
935 if( op
!=TK_INTEGER
|| pToken
->z
==0
936 || sqlite3GetInt32(pToken
->z
, &iValue
)==0 ){
937 nExtra
= pToken
->n
+1;
941 pNew
= sqlite3DbMallocRawNN(db
, sizeof(Expr
)+nExtra
);
943 memset(pNew
, 0, sizeof(Expr
));
948 pNew
->flags
|= EP_IntValue
|EP_Leaf
|(iValue
?EP_IsTrue
:EP_IsFalse
);
949 pNew
->u
.iValue
= iValue
;
951 pNew
->u
.zToken
= (char*)&pNew
[1];
952 assert( pToken
->z
!=0 || pToken
->n
==0 );
953 if( pToken
->n
) memcpy(pNew
->u
.zToken
, pToken
->z
, pToken
->n
);
954 pNew
->u
.zToken
[pToken
->n
] = 0;
955 if( dequote
&& sqlite3Isquote(pNew
->u
.zToken
[0]) ){
956 sqlite3DequoteExpr(pNew
);
960 #if SQLITE_MAX_EXPR_DEPTH>0
968 ** Allocate a new expression node from a zero-terminated token that has
969 ** already been dequoted.
972 sqlite3
*db
, /* Handle for sqlite3DbMallocZero() (may be null) */
973 int op
, /* Expression opcode */
974 const char *zToken
/* Token argument. Might be NULL */
978 x
.n
= sqlite3Strlen30(zToken
);
979 return sqlite3ExprAlloc(db
, op
, &x
, 0);
983 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
985 ** If pRoot==NULL that means that a memory allocation error has occurred.
986 ** In that case, delete the subtrees pLeft and pRight.
988 void sqlite3ExprAttachSubtrees(
995 assert( db
->mallocFailed
);
996 sqlite3ExprDelete(db
, pLeft
);
997 sqlite3ExprDelete(db
, pRight
);
999 assert( ExprUseXList(pRoot
) );
1000 assert( pRoot
->x
.pSelect
==0 );
1002 pRoot
->pRight
= pRight
;
1003 pRoot
->flags
|= EP_Propagate
& pRight
->flags
;
1004 #if SQLITE_MAX_EXPR_DEPTH>0
1005 pRoot
->nHeight
= pRight
->nHeight
+1;
1011 pRoot
->pLeft
= pLeft
;
1012 pRoot
->flags
|= EP_Propagate
& pLeft
->flags
;
1013 #if SQLITE_MAX_EXPR_DEPTH>0
1014 if( pLeft
->nHeight
>=pRoot
->nHeight
){
1015 pRoot
->nHeight
= pLeft
->nHeight
+1;
1023 ** Allocate an Expr node which joins as many as two subtrees.
1025 ** One or both of the subtrees can be NULL. Return a pointer to the new
1026 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1027 ** free the subtrees and return NULL.
1030 Parse
*pParse
, /* Parsing context */
1031 int op
, /* Expression opcode */
1032 Expr
*pLeft
, /* Left operand */
1033 Expr
*pRight
/* Right operand */
1036 p
= sqlite3DbMallocRawNN(pParse
->db
, sizeof(Expr
));
1038 memset(p
, 0, sizeof(Expr
));
1041 sqlite3ExprAttachSubtrees(pParse
->db
, p
, pLeft
, pRight
);
1042 sqlite3ExprCheckHeight(pParse
, p
->nHeight
);
1044 sqlite3ExprDelete(pParse
->db
, pLeft
);
1045 sqlite3ExprDelete(pParse
->db
, pRight
);
1051 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1052 ** do a memory allocation failure) then delete the pSelect object.
1054 void sqlite3PExprAddSelect(Parse
*pParse
, Expr
*pExpr
, Select
*pSelect
){
1056 pExpr
->x
.pSelect
= pSelect
;
1057 ExprSetProperty(pExpr
, EP_xIsSelect
|EP_Subquery
);
1058 sqlite3ExprSetHeightAndFlags(pParse
, pExpr
);
1060 assert( pParse
->db
->mallocFailed
);
1061 sqlite3SelectDelete(pParse
->db
, pSelect
);
1066 ** Expression list pEList is a list of vector values. This function
1067 ** converts the contents of pEList to a VALUES(...) Select statement
1068 ** returning 1 row for each element of the list. For example, the
1071 ** ( (1,2), (3,4) (5,6) )
1073 ** is translated to the equivalent of:
1075 ** VALUES(1,2), (3,4), (5,6)
1077 ** Each of the vector values in pEList must contain exactly nElem terms.
1078 ** If a list element that is not a vector or does not contain nElem terms,
1079 ** an error message is left in pParse.
1081 ** This is used as part of processing IN(...) expressions with a list
1082 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1084 Select
*sqlite3ExprListToValues(Parse
*pParse
, int nElem
, ExprList
*pEList
){
1088 for(ii
=0; ii
<pEList
->nExpr
; ii
++){
1090 Expr
*pExpr
= pEList
->a
[ii
].pExpr
;
1092 if( pExpr
->op
==TK_VECTOR
){
1093 assert( ExprUseXList(pExpr
) );
1094 nExprElem
= pExpr
->x
.pList
->nExpr
;
1098 if( nExprElem
!=nElem
){
1099 sqlite3ErrorMsg(pParse
, "IN(...) element has %d term%s - expected %d",
1100 nExprElem
, nExprElem
>1?"s":"", nElem
1104 assert( ExprUseXList(pExpr
) );
1105 pSel
= sqlite3SelectNew(pParse
, pExpr
->x
.pList
, 0, 0, 0, 0, 0, SF_Values
,0);
1110 pSel
->pPrior
= pRet
;
1116 if( pRet
&& pRet
->pPrior
){
1117 pRet
->selFlags
|= SF_MultiValue
;
1119 sqlite3ExprListDelete(pParse
->db
, pEList
);
1124 ** Join two expressions using an AND operator. If either expression is
1125 ** NULL, then just return the other expression.
1127 ** If one side or the other of the AND is known to be false, and neither side
1128 ** is part of an ON clause, then instead of returning an AND expression,
1129 ** just return a constant expression with a value of false.
1131 Expr
*sqlite3ExprAnd(Parse
*pParse
, Expr
*pLeft
, Expr
*pRight
){
1132 sqlite3
*db
= pParse
->db
;
1135 }else if( pRight
==0 ){
1138 u32 f
= pLeft
->flags
| pRight
->flags
;
1139 if( (f
&(EP_OuterON
|EP_InnerON
|EP_IsFalse
))==EP_IsFalse
1140 && !IN_RENAME_OBJECT
1142 sqlite3ExprDeferredDelete(pParse
, pLeft
);
1143 sqlite3ExprDeferredDelete(pParse
, pRight
);
1144 return sqlite3Expr(db
, TK_INTEGER
, "0");
1146 return sqlite3PExpr(pParse
, TK_AND
, pLeft
, pRight
);
1152 ** Construct a new expression node for a function with multiple
1155 Expr
*sqlite3ExprFunction(
1156 Parse
*pParse
, /* Parsing context */
1157 ExprList
*pList
, /* Argument list */
1158 const Token
*pToken
, /* Name of the function */
1159 int eDistinct
/* SF_Distinct or SF_ALL or 0 */
1162 sqlite3
*db
= pParse
->db
;
1164 pNew
= sqlite3ExprAlloc(db
, TK_FUNCTION
, pToken
, 1);
1166 sqlite3ExprListDelete(db
, pList
); /* Avoid memory leak when malloc fails */
1169 assert( !ExprHasProperty(pNew
, EP_InnerON
|EP_OuterON
) );
1170 pNew
->w
.iOfst
= (int)(pToken
->z
- pParse
->zTail
);
1172 && pList
->nExpr
> pParse
->db
->aLimit
[SQLITE_LIMIT_FUNCTION_ARG
]
1175 sqlite3ErrorMsg(pParse
, "too many arguments on function %T", pToken
);
1177 pNew
->x
.pList
= pList
;
1178 ExprSetProperty(pNew
, EP_HasFunc
);
1179 assert( ExprUseXList(pNew
) );
1180 sqlite3ExprSetHeightAndFlags(pParse
, pNew
);
1181 if( eDistinct
==SF_Distinct
) ExprSetProperty(pNew
, EP_Distinct
);
1186 ** Report an error when attempting to use an ORDER BY clause within
1187 ** the arguments of a non-aggregate function.
1189 void sqlite3ExprOrderByAggregateError(Parse
*pParse
, Expr
*p
){
1190 sqlite3ErrorMsg(pParse
,
1191 "ORDER BY may not be used with non-aggregate %#T()", p
1196 ** Attach an ORDER BY clause to a function call.
1198 ** functionname( arguments ORDER BY sortlist )
1199 ** \_____________________/ \______/
1202 ** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER
1203 ** and added to the Expr.pLeft field of the parent TK_FUNCTION node.
1205 void sqlite3ExprAddFunctionOrderBy(
1206 Parse
*pParse
, /* Parsing context */
1207 Expr
*pExpr
, /* The function call to which ORDER BY is to be added */
1208 ExprList
*pOrderBy
/* The ORDER BY clause to add */
1211 sqlite3
*db
= pParse
->db
;
1212 if( NEVER(pOrderBy
==0) ){
1213 assert( db
->mallocFailed
);
1217 assert( db
->mallocFailed
);
1218 sqlite3ExprListDelete(db
, pOrderBy
);
1221 assert( pExpr
->op
==TK_FUNCTION
);
1222 assert( pExpr
->pLeft
==0 );
1223 assert( ExprUseXList(pExpr
) );
1224 if( pExpr
->x
.pList
==0 || NEVER(pExpr
->x
.pList
->nExpr
==0) ){
1225 /* Ignore ORDER BY on zero-argument aggregates */
1226 sqlite3ParserAddCleanup(pParse
,
1227 (void(*)(sqlite3
*,void*))sqlite3ExprListDelete
,
1231 if( IsWindowFunc(pExpr
) ){
1232 sqlite3ExprOrderByAggregateError(pParse
, pExpr
);
1233 sqlite3ExprListDelete(db
, pOrderBy
);
1237 pOB
= sqlite3ExprAlloc(db
, TK_ORDER
, 0, 0);
1239 sqlite3ExprListDelete(db
, pOrderBy
);
1242 pOB
->x
.pList
= pOrderBy
;
1243 assert( ExprUseXList(pOB
) );
1245 ExprSetProperty(pOB
, EP_FullSize
);
1249 ** Check to see if a function is usable according to current access
1252 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1254 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1257 ** If the function is not usable, create an error.
1259 void sqlite3ExprFunctionUsable(
1260 Parse
*pParse
, /* Parsing and code generating context */
1261 const Expr
*pExpr
, /* The function invocation */
1262 const FuncDef
*pDef
/* The function being invoked */
1264 assert( !IN_RENAME_OBJECT
);
1265 assert( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0 );
1266 if( ExprHasProperty(pExpr
, EP_FromDDL
) ){
1267 if( (pDef
->funcFlags
& SQLITE_FUNC_DIRECT
)!=0
1268 || (pParse
->db
->flags
& SQLITE_TrustedSchema
)==0
1270 /* Functions prohibited in triggers and views if:
1271 ** (1) tagged with SQLITE_DIRECTONLY
1272 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1273 ** is tagged with SQLITE_FUNC_UNSAFE) and
1274 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1275 ** that the schema is possibly tainted).
1277 sqlite3ErrorMsg(pParse
, "unsafe use of %#T()", pExpr
);
1283 ** Assign a variable number to an expression that encodes a wildcard
1284 ** in the original SQL statement.
1286 ** Wildcards consisting of a single "?" are assigned the next sequential
1289 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1290 ** sure "nnn" is not too big to avoid a denial of service attack when
1291 ** the SQL statement comes from an external source.
1293 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1294 ** as the previous instance of the same wildcard. Or if this is the first
1295 ** instance of the wildcard, the next sequential variable number is
1298 void sqlite3ExprAssignVarNumber(Parse
*pParse
, Expr
*pExpr
, u32 n
){
1299 sqlite3
*db
= pParse
->db
;
1303 if( pExpr
==0 ) return;
1304 assert( !ExprHasProperty(pExpr
, EP_IntValue
|EP_Reduced
|EP_TokenOnly
) );
1305 z
= pExpr
->u
.zToken
;
1308 assert( n
==(u32
)sqlite3Strlen30(z
) );
1310 /* Wildcard of the form "?". Assign the next variable number */
1311 assert( z
[0]=='?' );
1312 x
= (ynVar
)(++pParse
->nVar
);
1316 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1317 ** use it as the variable number */
1320 if( n
==2 ){ /*OPTIMIZATION-IF-TRUE*/
1321 i
= z
[1]-'0'; /* The common case of ?N for a single digit N */
1324 bOk
= 0==sqlite3Atoi64(&z
[1], &i
, n
-1, SQLITE_UTF8
);
1328 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]-1 );
1329 testcase( i
==db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] );
1330 if( bOk
==0 || i
<1 || i
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
1331 sqlite3ErrorMsg(pParse
, "variable number must be between ?1 and ?%d",
1332 db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
]);
1333 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1337 if( x
>pParse
->nVar
){
1338 pParse
->nVar
= (int)x
;
1340 }else if( sqlite3VListNumToName(pParse
->pVList
, x
)==0 ){
1344 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1345 ** number as the prior appearance of the same name, or if the name
1346 ** has never appeared before, reuse the same variable number
1348 x
= (ynVar
)sqlite3VListNameToNum(pParse
->pVList
, z
, n
);
1350 x
= (ynVar
)(++pParse
->nVar
);
1355 pParse
->pVList
= sqlite3VListAdd(db
, pParse
->pVList
, z
, n
, x
);
1359 if( x
>db
->aLimit
[SQLITE_LIMIT_VARIABLE_NUMBER
] ){
1360 sqlite3ErrorMsg(pParse
, "too many SQL variables");
1361 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1366 ** Recursively delete an expression tree.
1368 static SQLITE_NOINLINE
void sqlite3ExprDeleteNN(sqlite3
*db
, Expr
*p
){
1371 assert( !ExprUseUValue(p
) || p
->u
.iValue
>=0 );
1372 assert( !ExprUseYWin(p
) || !ExprUseYSub(p
) );
1373 assert( !ExprUseYWin(p
) || p
->y
.pWin
!=0 || db
->mallocFailed
);
1374 assert( p
->op
!=TK_FUNCTION
|| !ExprUseYSub(p
) );
1376 if( ExprHasProperty(p
, EP_Leaf
) && !ExprHasProperty(p
, EP_TokenOnly
) ){
1377 assert( p
->pLeft
==0 );
1378 assert( p
->pRight
==0 );
1379 assert( !ExprUseXSelect(p
) || p
->x
.pSelect
==0 );
1380 assert( !ExprUseXList(p
) || p
->x
.pList
==0 );
1383 if( !ExprHasProperty(p
, (EP_TokenOnly
|EP_Leaf
)) ){
1384 /* The Expr.x union is never used at the same time as Expr.pRight */
1385 assert( (ExprUseXList(p
) && p
->x
.pList
==0) || p
->pRight
==0 );
1386 if( p
->pLeft
&& p
->op
!=TK_SELECT_COLUMN
) sqlite3ExprDeleteNN(db
, p
->pLeft
);
1388 assert( !ExprHasProperty(p
, EP_WinFunc
) );
1389 sqlite3ExprDeleteNN(db
, p
->pRight
);
1390 }else if( ExprUseXSelect(p
) ){
1391 assert( !ExprHasProperty(p
, EP_WinFunc
) );
1392 sqlite3SelectDelete(db
, p
->x
.pSelect
);
1394 sqlite3ExprListDelete(db
, p
->x
.pList
);
1395 #ifndef SQLITE_OMIT_WINDOWFUNC
1396 if( ExprHasProperty(p
, EP_WinFunc
) ){
1397 sqlite3WindowDelete(db
, p
->y
.pWin
);
1402 if( !ExprHasProperty(p
, EP_Static
) ){
1403 sqlite3DbNNFreeNN(db
, p
);
1406 void sqlite3ExprDelete(sqlite3
*db
, Expr
*p
){
1407 if( p
) sqlite3ExprDeleteNN(db
, p
);
1411 ** Clear both elements of an OnOrUsing object
1413 void sqlite3ClearOnOrUsing(sqlite3
*db
, OnOrUsing
*p
){
1415 /* Nothing to clear */
1417 sqlite3ExprDeleteNN(db
, p
->pOn
);
1418 }else if( p
->pUsing
){
1419 sqlite3IdListDelete(db
, p
->pUsing
);
1424 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1425 ** This is similar to sqlite3ExprDelete() except that the delete is
1426 ** deferred until the pParse is deleted.
1428 ** The pExpr might be deleted immediately on an OOM error.
1430 ** The deferred delete is (currently) implemented by adding the
1431 ** pExpr to the pParse->pConstExpr list with a register number of 0.
1433 void sqlite3ExprDeferredDelete(Parse
*pParse
, Expr
*pExpr
){
1434 sqlite3ParserAddCleanup(pParse
,
1435 (void(*)(sqlite3
*,void*))sqlite3ExprDelete
,
1439 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1442 void sqlite3ExprUnmapAndDelete(Parse
*pParse
, Expr
*p
){
1444 if( IN_RENAME_OBJECT
){
1445 sqlite3RenameExprUnmap(pParse
, p
);
1447 sqlite3ExprDeleteNN(pParse
->db
, p
);
1452 ** Return the number of bytes allocated for the expression structure
1453 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1454 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1456 static int exprStructSize(const Expr
*p
){
1457 if( ExprHasProperty(p
, EP_TokenOnly
) ) return EXPR_TOKENONLYSIZE
;
1458 if( ExprHasProperty(p
, EP_Reduced
) ) return EXPR_REDUCEDSIZE
;
1459 return EXPR_FULLSIZE
;
1463 ** The dupedExpr*Size() routines each return the number of bytes required
1464 ** to store a copy of an expression or expression tree. They differ in
1465 ** how much of the tree is measured.
1467 ** dupedExprStructSize() Size of only the Expr structure
1468 ** dupedExprNodeSize() Size of Expr + space for token
1469 ** dupedExprSize() Expr + token + subtree components
1471 ***************************************************************************
1473 ** The dupedExprStructSize() function returns two values OR-ed together:
1474 ** (1) the space required for a copy of the Expr structure only and
1475 ** (2) the EP_xxx flags that indicate what the structure size should be.
1476 ** The return values is always one of:
1479 ** EXPR_REDUCEDSIZE | EP_Reduced
1480 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1482 ** The size of the structure can be found by masking the return value
1483 ** of this routine with 0xfff. The flags can be found by masking the
1484 ** return value with EP_Reduced|EP_TokenOnly.
1486 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1487 ** (unreduced) Expr objects as they or originally constructed by the parser.
1488 ** During expression analysis, extra information is computed and moved into
1489 ** later parts of the Expr object and that extra information might get chopped
1490 ** off if the expression is reduced. Note also that it does not work to
1491 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1492 ** to reduce a pristine expression tree from the parser. The implementation
1493 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1494 ** to enforce this constraint.
1496 static int dupedExprStructSize(const Expr
*p
, int flags
){
1498 assert( flags
==EXPRDUP_REDUCE
|| flags
==0 ); /* Only one flag value allowed */
1499 assert( EXPR_FULLSIZE
<=0xfff );
1500 assert( (0xfff & (EP_Reduced
|EP_TokenOnly
))==0 );
1501 if( 0==flags
|| ExprHasProperty(p
, EP_FullSize
) ){
1502 nSize
= EXPR_FULLSIZE
;
1504 assert( !ExprHasProperty(p
, EP_TokenOnly
|EP_Reduced
) );
1505 assert( !ExprHasProperty(p
, EP_OuterON
) );
1506 assert( !ExprHasVVAProperty(p
, EP_NoReduce
) );
1507 if( p
->pLeft
|| p
->x
.pList
){
1508 nSize
= EXPR_REDUCEDSIZE
| EP_Reduced
;
1510 assert( p
->pRight
==0 );
1511 nSize
= EXPR_TOKENONLYSIZE
| EP_TokenOnly
;
1518 ** This function returns the space in bytes required to store the copy
1519 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1520 ** string is defined.)
1522 static int dupedExprNodeSize(const Expr
*p
, int flags
){
1523 int nByte
= dupedExprStructSize(p
, flags
) & 0xfff;
1524 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1525 nByte
+= sqlite3Strlen30NN(p
->u
.zToken
)+1;
1527 return ROUND8(nByte
);
1531 ** Return the number of bytes required to create a duplicate of the
1532 ** expression passed as the first argument.
1534 ** The value returned includes space to create a copy of the Expr struct
1535 ** itself and the buffer referred to by Expr.u.zToken, if any.
1537 ** The return value includes space to duplicate all Expr nodes in the
1538 ** tree formed by Expr.pLeft and Expr.pRight, but not any other
1539 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
1541 static int dupedExprSize(const Expr
*p
){
1544 nByte
= dupedExprNodeSize(p
, EXPRDUP_REDUCE
);
1545 if( p
->pLeft
) nByte
+= dupedExprSize(p
->pLeft
);
1546 if( p
->pRight
) nByte
+= dupedExprSize(p
->pRight
);
1547 assert( nByte
==ROUND8(nByte
) );
1552 ** An EdupBuf is a memory allocation used to stored multiple Expr objects
1553 ** together with their Expr.zToken content. This is used to help implement
1554 ** compression while doing sqlite3ExprDup(). The top-level Expr does the
1555 ** allocation for itself and many of its decendents, then passes an instance
1556 ** of the structure down into exprDup() so that they decendents can have
1557 ** access to that memory.
1559 typedef struct EdupBuf EdupBuf
;
1561 u8
*zAlloc
; /* Memory space available for storage */
1563 u8
*zEnd
; /* First byte past the end of memory */
1568 ** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
1569 ** is not NULL then it points to memory that can be used to store a copy
1570 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf
1571 ** is updated with the new buffer tail prior to returning.
1573 static Expr
*exprDup(
1574 sqlite3
*db
, /* Database connection (for memory allocation) */
1575 const Expr
*p
, /* Expr tree to be duplicated */
1576 int dupFlags
, /* EXPRDUP_REDUCE for compression. 0 if not */
1577 EdupBuf
*pEdupBuf
/* Preallocated storage space, or NULL */
1579 Expr
*pNew
; /* Value to return */
1580 EdupBuf sEdupBuf
; /* Memory space from which to build Expr object */
1581 u32 staticFlag
; /* EP_Static if space not obtained from malloc */
1582 int nToken
= -1; /* Space needed for p->u.zToken. -1 means unknown */
1586 assert( dupFlags
==0 || dupFlags
==EXPRDUP_REDUCE
);
1587 assert( pEdupBuf
==0 || dupFlags
==EXPRDUP_REDUCE
);
1589 /* Figure out where to write the new Expr structure. */
1591 sEdupBuf
.zAlloc
= pEdupBuf
->zAlloc
;
1593 sEdupBuf
.zEnd
= pEdupBuf
->zEnd
;
1595 staticFlag
= EP_Static
;
1596 assert( sEdupBuf
.zAlloc
!=0 );
1597 assert( dupFlags
==EXPRDUP_REDUCE
);
1601 nAlloc
= dupedExprSize(p
);
1602 }else if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1603 nToken
= sqlite3Strlen30NN(p
->u
.zToken
)+1;
1604 nAlloc
= ROUND8(EXPR_FULLSIZE
+ nToken
);
1607 nAlloc
= ROUND8(EXPR_FULLSIZE
);
1609 assert( nAlloc
==ROUND8(nAlloc
) );
1610 sEdupBuf
.zAlloc
= sqlite3DbMallocRawNN(db
, nAlloc
);
1612 sEdupBuf
.zEnd
= sEdupBuf
.zAlloc
? sEdupBuf
.zAlloc
+nAlloc
: 0;
1617 pNew
= (Expr
*)sEdupBuf
.zAlloc
;
1618 assert( EIGHT_BYTE_ALIGNMENT(pNew
) );
1621 /* Set nNewSize to the size allocated for the structure pointed to
1622 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1623 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1624 ** by the copy of the p->u.zToken string (if any).
1626 const unsigned nStructSize
= dupedExprStructSize(p
, dupFlags
);
1627 int nNewSize
= nStructSize
& 0xfff;
1629 if( !ExprHasProperty(p
, EP_IntValue
) && p
->u
.zToken
){
1630 nToken
= sqlite3Strlen30(p
->u
.zToken
) + 1;
1636 assert( (int)(sEdupBuf
.zEnd
- sEdupBuf
.zAlloc
) >= nNewSize
+nToken
);
1637 assert( ExprHasProperty(p
, EP_Reduced
)==0 );
1638 memcpy(sEdupBuf
.zAlloc
, p
, nNewSize
);
1640 u32 nSize
= (u32
)exprStructSize(p
);
1641 assert( (int)(sEdupBuf
.zEnd
- sEdupBuf
.zAlloc
) >=
1642 (int)EXPR_FULLSIZE
+nToken
);
1643 memcpy(sEdupBuf
.zAlloc
, p
, nSize
);
1644 if( nSize
<EXPR_FULLSIZE
){
1645 memset(&sEdupBuf
.zAlloc
[nSize
], 0, EXPR_FULLSIZE
-nSize
);
1647 nNewSize
= EXPR_FULLSIZE
;
1650 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1651 pNew
->flags
&= ~(EP_Reduced
|EP_TokenOnly
|EP_Static
);
1652 pNew
->flags
|= nStructSize
& (EP_Reduced
|EP_TokenOnly
);
1653 pNew
->flags
|= staticFlag
;
1654 ExprClearVVAProperties(pNew
);
1656 ExprSetVVAProperty(pNew
, EP_Immutable
);
1659 /* Copy the p->u.zToken string, if any. */
1660 assert( nToken
>=0 );
1662 char *zToken
= pNew
->u
.zToken
= (char*)&sEdupBuf
.zAlloc
[nNewSize
];
1663 memcpy(zToken
, p
->u
.zToken
, nToken
);
1666 sEdupBuf
.zAlloc
+= ROUND8(nNewSize
);
1668 if( ((p
->flags
|pNew
->flags
)&(EP_TokenOnly
|EP_Leaf
))==0 ){
1670 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1671 if( ExprUseXSelect(p
) ){
1672 pNew
->x
.pSelect
= sqlite3SelectDup(db
, p
->x
.pSelect
, dupFlags
);
1674 pNew
->x
.pList
= sqlite3ExprListDup(db
, p
->x
.pList
,
1675 p
->op
!=TK_ORDER
? dupFlags
: 0);
1678 #ifndef SQLITE_OMIT_WINDOWFUNC
1679 if( ExprHasProperty(p
, EP_WinFunc
) ){
1680 pNew
->y
.pWin
= sqlite3WindowDup(db
, pNew
, p
->y
.pWin
);
1681 assert( ExprHasProperty(pNew
, EP_WinFunc
) );
1683 #endif /* SQLITE_OMIT_WINDOWFUNC */
1685 /* Fill in pNew->pLeft and pNew->pRight. */
1687 if( p
->op
==TK_SELECT_COLUMN
){
1688 pNew
->pLeft
= p
->pLeft
;
1689 assert( p
->pRight
==0
1690 || p
->pRight
==p
->pLeft
1691 || ExprHasProperty(p
->pLeft
, EP_Subquery
) );
1693 pNew
->pLeft
= p
->pLeft
?
1694 exprDup(db
, p
->pLeft
, EXPRDUP_REDUCE
, &sEdupBuf
) : 0;
1696 pNew
->pRight
= p
->pRight
?
1697 exprDup(db
, p
->pRight
, EXPRDUP_REDUCE
, &sEdupBuf
) : 0;
1699 if( p
->op
==TK_SELECT_COLUMN
){
1700 pNew
->pLeft
= p
->pLeft
;
1701 assert( p
->pRight
==0
1702 || p
->pRight
==p
->pLeft
1703 || ExprHasProperty(p
->pLeft
, EP_Subquery
) );
1705 pNew
->pLeft
= sqlite3ExprDup(db
, p
->pLeft
, 0);
1707 pNew
->pRight
= sqlite3ExprDup(db
, p
->pRight
, 0);
1711 if( pEdupBuf
) memcpy(pEdupBuf
, &sEdupBuf
, sizeof(sEdupBuf
));
1712 assert( sEdupBuf
.zAlloc
<= sEdupBuf
.zEnd
);
1717 ** Create and return a deep copy of the object passed as the second
1718 ** argument. If an OOM condition is encountered, NULL is returned
1719 ** and the db->mallocFailed flag set.
1721 #ifndef SQLITE_OMIT_CTE
1722 With
*sqlite3WithDup(sqlite3
*db
, With
*p
){
1725 sqlite3_int64 nByte
= sizeof(*p
) + sizeof(p
->a
[0]) * (p
->nCte
-1);
1726 pRet
= sqlite3DbMallocZero(db
, nByte
);
1729 pRet
->nCte
= p
->nCte
;
1730 for(i
=0; i
<p
->nCte
; i
++){
1731 pRet
->a
[i
].pSelect
= sqlite3SelectDup(db
, p
->a
[i
].pSelect
, 0);
1732 pRet
->a
[i
].pCols
= sqlite3ExprListDup(db
, p
->a
[i
].pCols
, 0);
1733 pRet
->a
[i
].zName
= sqlite3DbStrDup(db
, p
->a
[i
].zName
);
1734 pRet
->a
[i
].eM10d
= p
->a
[i
].eM10d
;
1741 # define sqlite3WithDup(x,y) 0
1744 #ifndef SQLITE_OMIT_WINDOWFUNC
1746 ** The gatherSelectWindows() procedure and its helper routine
1747 ** gatherSelectWindowsCallback() are used to scan all the expressions
1748 ** an a newly duplicated SELECT statement and gather all of the Window
1749 ** objects found there, assembling them onto the linked list at Select->pWin.
1751 static int gatherSelectWindowsCallback(Walker
*pWalker
, Expr
*pExpr
){
1752 if( pExpr
->op
==TK_FUNCTION
&& ExprHasProperty(pExpr
, EP_WinFunc
) ){
1753 Select
*pSelect
= pWalker
->u
.pSelect
;
1754 Window
*pWin
= pExpr
->y
.pWin
;
1756 assert( IsWindowFunc(pExpr
) );
1757 assert( pWin
->ppThis
==0 );
1758 sqlite3WindowLink(pSelect
, pWin
);
1760 return WRC_Continue
;
1762 static int gatherSelectWindowsSelectCallback(Walker
*pWalker
, Select
*p
){
1763 return p
==pWalker
->u
.pSelect
? WRC_Continue
: WRC_Prune
;
1765 static void gatherSelectWindows(Select
*p
){
1767 w
.xExprCallback
= gatherSelectWindowsCallback
;
1768 w
.xSelectCallback
= gatherSelectWindowsSelectCallback
;
1769 w
.xSelectCallback2
= 0;
1772 sqlite3WalkSelect(&w
, p
);
1778 ** The following group of routines make deep copies of expressions,
1779 ** expression lists, ID lists, and select statements. The copies can
1780 ** be deleted (by being passed to their respective ...Delete() routines)
1781 ** without effecting the originals.
1783 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1784 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1785 ** by subsequent calls to sqlite*ListAppend() routines.
1787 ** Any tables that the SrcList might point to are not duplicated.
1789 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1790 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1791 ** truncated version of the usual Expr structure that will be stored as
1792 ** part of the in-memory representation of the database schema.
1794 Expr
*sqlite3ExprDup(sqlite3
*db
, const Expr
*p
, int flags
){
1795 assert( flags
==0 || flags
==EXPRDUP_REDUCE
);
1796 return p
? exprDup(db
, p
, flags
, 0) : 0;
1798 ExprList
*sqlite3ExprListDup(sqlite3
*db
, const ExprList
*p
, int flags
){
1800 struct ExprList_item
*pItem
;
1801 const struct ExprList_item
*pOldItem
;
1803 Expr
*pPriorSelectColOld
= 0;
1804 Expr
*pPriorSelectColNew
= 0;
1806 if( p
==0 ) return 0;
1807 pNew
= sqlite3DbMallocRawNN(db
, sqlite3DbMallocSize(db
, p
));
1808 if( pNew
==0 ) return 0;
1809 pNew
->nExpr
= p
->nExpr
;
1810 pNew
->nAlloc
= p
->nAlloc
;
1813 for(i
=0; i
<p
->nExpr
; i
++, pItem
++, pOldItem
++){
1814 Expr
*pOldExpr
= pOldItem
->pExpr
;
1816 pItem
->pExpr
= sqlite3ExprDup(db
, pOldExpr
, flags
);
1818 && pOldExpr
->op
==TK_SELECT_COLUMN
1819 && (pNewExpr
= pItem
->pExpr
)!=0
1821 if( pNewExpr
->pRight
){
1822 pPriorSelectColOld
= pOldExpr
->pRight
;
1823 pPriorSelectColNew
= pNewExpr
->pRight
;
1824 pNewExpr
->pLeft
= pNewExpr
->pRight
;
1826 if( pOldExpr
->pLeft
!=pPriorSelectColOld
){
1827 pPriorSelectColOld
= pOldExpr
->pLeft
;
1828 pPriorSelectColNew
= sqlite3ExprDup(db
, pPriorSelectColOld
, flags
);
1829 pNewExpr
->pRight
= pPriorSelectColNew
;
1831 pNewExpr
->pLeft
= pPriorSelectColNew
;
1834 pItem
->zEName
= sqlite3DbStrDup(db
, pOldItem
->zEName
);
1835 pItem
->fg
= pOldItem
->fg
;
1837 pItem
->u
= pOldItem
->u
;
1843 ** If cursors, triggers, views and subqueries are all omitted from
1844 ** the build, then none of the following routines, except for
1845 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1846 ** called with a NULL argument.
1848 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1849 || !defined(SQLITE_OMIT_SUBQUERY)
1850 SrcList
*sqlite3SrcListDup(sqlite3
*db
, const SrcList
*p
, int flags
){
1855 if( p
==0 ) return 0;
1856 nByte
= sizeof(*p
) + (p
->nSrc
>0 ? sizeof(p
->a
[0]) * (p
->nSrc
-1) : 0);
1857 pNew
= sqlite3DbMallocRawNN(db
, nByte
);
1858 if( pNew
==0 ) return 0;
1859 pNew
->nSrc
= pNew
->nAlloc
= p
->nSrc
;
1860 for(i
=0; i
<p
->nSrc
; i
++){
1861 SrcItem
*pNewItem
= &pNew
->a
[i
];
1862 const SrcItem
*pOldItem
= &p
->a
[i
];
1864 pNewItem
->pSchema
= pOldItem
->pSchema
;
1865 pNewItem
->zDatabase
= sqlite3DbStrDup(db
, pOldItem
->zDatabase
);
1866 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1867 pNewItem
->zAlias
= sqlite3DbStrDup(db
, pOldItem
->zAlias
);
1868 pNewItem
->fg
= pOldItem
->fg
;
1869 pNewItem
->iCursor
= pOldItem
->iCursor
;
1870 pNewItem
->addrFillSub
= pOldItem
->addrFillSub
;
1871 pNewItem
->regReturn
= pOldItem
->regReturn
;
1872 if( pNewItem
->fg
.isIndexedBy
){
1873 pNewItem
->u1
.zIndexedBy
= sqlite3DbStrDup(db
, pOldItem
->u1
.zIndexedBy
);
1875 pNewItem
->u2
= pOldItem
->u2
;
1876 if( pNewItem
->fg
.isCte
){
1877 pNewItem
->u2
.pCteUse
->nUse
++;
1879 if( pNewItem
->fg
.isTabFunc
){
1880 pNewItem
->u1
.pFuncArg
=
1881 sqlite3ExprListDup(db
, pOldItem
->u1
.pFuncArg
, flags
);
1883 pTab
= pNewItem
->pTab
= pOldItem
->pTab
;
1887 pNewItem
->pSelect
= sqlite3SelectDup(db
, pOldItem
->pSelect
, flags
);
1888 if( pOldItem
->fg
.isUsing
){
1889 assert( pNewItem
->fg
.isUsing
);
1890 pNewItem
->u3
.pUsing
= sqlite3IdListDup(db
, pOldItem
->u3
.pUsing
);
1892 pNewItem
->u3
.pOn
= sqlite3ExprDup(db
, pOldItem
->u3
.pOn
, flags
);
1894 pNewItem
->colUsed
= pOldItem
->colUsed
;
1898 IdList
*sqlite3IdListDup(sqlite3
*db
, const IdList
*p
){
1902 if( p
==0 ) return 0;
1903 assert( p
->eU4
!=EU4_EXPR
);
1904 pNew
= sqlite3DbMallocRawNN(db
, sizeof(*pNew
)+(p
->nId
-1)*sizeof(p
->a
[0]) );
1905 if( pNew
==0 ) return 0;
1908 for(i
=0; i
<p
->nId
; i
++){
1909 struct IdList_item
*pNewItem
= &pNew
->a
[i
];
1910 const struct IdList_item
*pOldItem
= &p
->a
[i
];
1911 pNewItem
->zName
= sqlite3DbStrDup(db
, pOldItem
->zName
);
1912 pNewItem
->u4
= pOldItem
->u4
;
1916 Select
*sqlite3SelectDup(sqlite3
*db
, const Select
*pDup
, int flags
){
1919 Select
**pp
= &pRet
;
1923 for(p
=pDup
; p
; p
=p
->pPrior
){
1924 Select
*pNew
= sqlite3DbMallocRawNN(db
, sizeof(*p
) );
1925 if( pNew
==0 ) break;
1926 pNew
->pEList
= sqlite3ExprListDup(db
, p
->pEList
, flags
);
1927 pNew
->pSrc
= sqlite3SrcListDup(db
, p
->pSrc
, flags
);
1928 pNew
->pWhere
= sqlite3ExprDup(db
, p
->pWhere
, flags
);
1929 pNew
->pGroupBy
= sqlite3ExprListDup(db
, p
->pGroupBy
, flags
);
1930 pNew
->pHaving
= sqlite3ExprDup(db
, p
->pHaving
, flags
);
1931 pNew
->pOrderBy
= sqlite3ExprListDup(db
, p
->pOrderBy
, flags
);
1933 pNew
->pNext
= pNext
;
1935 pNew
->pLimit
= sqlite3ExprDup(db
, p
->pLimit
, flags
);
1938 pNew
->selFlags
= p
->selFlags
& ~SF_UsesEphemeral
;
1939 pNew
->addrOpenEphm
[0] = -1;
1940 pNew
->addrOpenEphm
[1] = -1;
1941 pNew
->nSelectRow
= p
->nSelectRow
;
1942 pNew
->pWith
= sqlite3WithDup(db
, p
->pWith
);
1943 #ifndef SQLITE_OMIT_WINDOWFUNC
1945 pNew
->pWinDefn
= sqlite3WindowListDup(db
, p
->pWinDefn
);
1946 if( p
->pWin
&& db
->mallocFailed
==0 ) gatherSelectWindows(pNew
);
1948 pNew
->selId
= p
->selId
;
1949 if( db
->mallocFailed
){
1950 /* Any prior OOM might have left the Select object incomplete.
1951 ** Delete the whole thing rather than allow an incomplete Select
1952 ** to be used by the code generator. */
1954 sqlite3SelectDelete(db
, pNew
);
1965 Select
*sqlite3SelectDup(sqlite3
*db
, const Select
*p
, int flags
){
1973 ** Add a new element to the end of an expression list. If pList is
1974 ** initially NULL, then create a new expression list.
1976 ** The pList argument must be either NULL or a pointer to an ExprList
1977 ** obtained from a prior call to sqlite3ExprListAppend().
1979 ** If a memory allocation error occurs, the entire list is freed and
1980 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1981 ** that the new entry was successfully appended.
1983 static const struct ExprList_item zeroItem
= {0};
1984 SQLITE_NOINLINE ExprList
*sqlite3ExprListAppendNew(
1985 sqlite3
*db
, /* Database handle. Used for memory allocation */
1986 Expr
*pExpr
/* Expression to be appended. Might be NULL */
1988 struct ExprList_item
*pItem
;
1991 pList
= sqlite3DbMallocRawNN(db
, sizeof(ExprList
)+sizeof(pList
->a
[0])*4 );
1993 sqlite3ExprDelete(db
, pExpr
);
1998 pItem
= &pList
->a
[0];
2000 pItem
->pExpr
= pExpr
;
2003 SQLITE_NOINLINE ExprList
*sqlite3ExprListAppendGrow(
2004 sqlite3
*db
, /* Database handle. Used for memory allocation */
2005 ExprList
*pList
, /* List to which to append. Might be NULL */
2006 Expr
*pExpr
/* Expression to be appended. Might be NULL */
2008 struct ExprList_item
*pItem
;
2011 pNew
= sqlite3DbRealloc(db
, pList
,
2012 sizeof(*pList
)+(pList
->nAlloc
-1)*sizeof(pList
->a
[0]));
2014 sqlite3ExprListDelete(db
, pList
);
2015 sqlite3ExprDelete(db
, pExpr
);
2020 pItem
= &pList
->a
[pList
->nExpr
++];
2022 pItem
->pExpr
= pExpr
;
2025 ExprList
*sqlite3ExprListAppend(
2026 Parse
*pParse
, /* Parsing context */
2027 ExprList
*pList
, /* List to which to append. Might be NULL */
2028 Expr
*pExpr
/* Expression to be appended. Might be NULL */
2030 struct ExprList_item
*pItem
;
2032 return sqlite3ExprListAppendNew(pParse
->db
,pExpr
);
2034 if( pList
->nAlloc
<pList
->nExpr
+1 ){
2035 return sqlite3ExprListAppendGrow(pParse
->db
,pList
,pExpr
);
2037 pItem
= &pList
->a
[pList
->nExpr
++];
2039 pItem
->pExpr
= pExpr
;
2044 ** pColumns and pExpr form a vector assignment which is part of the SET
2045 ** clause of an UPDATE statement. Like this:
2047 ** (a,b,c) = (expr1,expr2,expr3)
2048 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
2050 ** For each term of the vector assignment, append new entries to the
2051 ** expression list pList. In the case of a subquery on the RHS, append
2052 ** TK_SELECT_COLUMN expressions.
2054 ExprList
*sqlite3ExprListAppendVector(
2055 Parse
*pParse
, /* Parsing context */
2056 ExprList
*pList
, /* List to which to append. Might be NULL */
2057 IdList
*pColumns
, /* List of names of LHS of the assignment */
2058 Expr
*pExpr
/* Vector expression to be appended. Might be NULL */
2060 sqlite3
*db
= pParse
->db
;
2063 int iFirst
= pList
? pList
->nExpr
: 0;
2064 /* pColumns can only be NULL due to an OOM but an OOM will cause an
2065 ** exit prior to this routine being invoked */
2066 if( NEVER(pColumns
==0) ) goto vector_append_error
;
2067 if( pExpr
==0 ) goto vector_append_error
;
2069 /* If the RHS is a vector, then we can immediately check to see that
2070 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
2071 ** wildcards ("*") in the result set of the SELECT must be expanded before
2072 ** we can do the size check, so defer the size check until code generation.
2074 if( pExpr
->op
!=TK_SELECT
&& pColumns
->nId
!=(n
=sqlite3ExprVectorSize(pExpr
)) ){
2075 sqlite3ErrorMsg(pParse
, "%d columns assigned %d values",
2077 goto vector_append_error
;
2080 for(i
=0; i
<pColumns
->nId
; i
++){
2081 Expr
*pSubExpr
= sqlite3ExprForVectorField(pParse
, pExpr
, i
, pColumns
->nId
);
2082 assert( pSubExpr
!=0 || db
->mallocFailed
);
2083 if( pSubExpr
==0 ) continue;
2084 pList
= sqlite3ExprListAppend(pParse
, pList
, pSubExpr
);
2086 assert( pList
->nExpr
==iFirst
+i
+1 );
2087 pList
->a
[pList
->nExpr
-1].zEName
= pColumns
->a
[i
].zName
;
2088 pColumns
->a
[i
].zName
= 0;
2092 if( !db
->mallocFailed
&& pExpr
->op
==TK_SELECT
&& ALWAYS(pList
!=0) ){
2093 Expr
*pFirst
= pList
->a
[iFirst
].pExpr
;
2094 assert( pFirst
!=0 );
2095 assert( pFirst
->op
==TK_SELECT_COLUMN
);
2097 /* Store the SELECT statement in pRight so it will be deleted when
2098 ** sqlite3ExprListDelete() is called */
2099 pFirst
->pRight
= pExpr
;
2102 /* Remember the size of the LHS in iTable so that we can check that
2103 ** the RHS and LHS sizes match during code generation. */
2104 pFirst
->iTable
= pColumns
->nId
;
2107 vector_append_error
:
2108 sqlite3ExprUnmapAndDelete(pParse
, pExpr
);
2109 sqlite3IdListDelete(db
, pColumns
);
2114 ** Set the sort order for the last element on the given ExprList.
2116 void sqlite3ExprListSetSortOrder(ExprList
*p
, int iSortOrder
, int eNulls
){
2117 struct ExprList_item
*pItem
;
2119 assert( p
->nExpr
>0 );
2121 assert( SQLITE_SO_UNDEFINED
<0 && SQLITE_SO_ASC
==0 && SQLITE_SO_DESC
>0 );
2122 assert( iSortOrder
==SQLITE_SO_UNDEFINED
2123 || iSortOrder
==SQLITE_SO_ASC
2124 || iSortOrder
==SQLITE_SO_DESC
2126 assert( eNulls
==SQLITE_SO_UNDEFINED
2127 || eNulls
==SQLITE_SO_ASC
2128 || eNulls
==SQLITE_SO_DESC
2131 pItem
= &p
->a
[p
->nExpr
-1];
2132 assert( pItem
->fg
.bNulls
==0 );
2133 if( iSortOrder
==SQLITE_SO_UNDEFINED
){
2134 iSortOrder
= SQLITE_SO_ASC
;
2136 pItem
->fg
.sortFlags
= (u8
)iSortOrder
;
2138 if( eNulls
!=SQLITE_SO_UNDEFINED
){
2139 pItem
->fg
.bNulls
= 1;
2140 if( iSortOrder
!=eNulls
){
2141 pItem
->fg
.sortFlags
|= KEYINFO_ORDER_BIGNULL
;
2147 ** Set the ExprList.a[].zEName element of the most recently added item
2148 ** on the expression list.
2150 ** pList might be NULL following an OOM error. But pName should never be
2151 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2154 void sqlite3ExprListSetName(
2155 Parse
*pParse
, /* Parsing context */
2156 ExprList
*pList
, /* List to which to add the span. */
2157 const Token
*pName
, /* Name to be added */
2158 int dequote
/* True to cause the name to be dequoted */
2160 assert( pList
!=0 || pParse
->db
->mallocFailed
!=0 );
2161 assert( pParse
->eParseMode
!=PARSE_MODE_UNMAP
|| dequote
==0 );
2163 struct ExprList_item
*pItem
;
2164 assert( pList
->nExpr
>0 );
2165 pItem
= &pList
->a
[pList
->nExpr
-1];
2166 assert( pItem
->zEName
==0 );
2167 assert( pItem
->fg
.eEName
==ENAME_NAME
);
2168 pItem
->zEName
= sqlite3DbStrNDup(pParse
->db
, pName
->z
, pName
->n
);
2170 /* If dequote==0, then pName->z does not point to part of a DDL
2171 ** statement handled by the parser. And so no token need be added
2172 ** to the token-map. */
2173 sqlite3Dequote(pItem
->zEName
);
2174 if( IN_RENAME_OBJECT
){
2175 sqlite3RenameTokenMap(pParse
, (const void*)pItem
->zEName
, pName
);
2182 ** Set the ExprList.a[].zSpan element of the most recently added item
2183 ** on the expression list.
2185 ** pList might be NULL following an OOM error. But pSpan should never be
2186 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2189 void sqlite3ExprListSetSpan(
2190 Parse
*pParse
, /* Parsing context */
2191 ExprList
*pList
, /* List to which to add the span. */
2192 const char *zStart
, /* Start of the span */
2193 const char *zEnd
/* End of the span */
2195 sqlite3
*db
= pParse
->db
;
2196 assert( pList
!=0 || db
->mallocFailed
!=0 );
2198 struct ExprList_item
*pItem
= &pList
->a
[pList
->nExpr
-1];
2199 assert( pList
->nExpr
>0 );
2200 if( pItem
->zEName
==0 ){
2201 pItem
->zEName
= sqlite3DbSpanDup(db
, zStart
, zEnd
);
2202 pItem
->fg
.eEName
= ENAME_SPAN
;
2208 ** If the expression list pEList contains more than iLimit elements,
2209 ** leave an error message in pParse.
2211 void sqlite3ExprListCheckLength(
2216 int mx
= pParse
->db
->aLimit
[SQLITE_LIMIT_COLUMN
];
2217 testcase( pEList
&& pEList
->nExpr
==mx
);
2218 testcase( pEList
&& pEList
->nExpr
==mx
+1 );
2219 if( pEList
&& pEList
->nExpr
>mx
){
2220 sqlite3ErrorMsg(pParse
, "too many columns in %s", zObject
);
2225 ** Delete an entire expression list.
2227 static SQLITE_NOINLINE
void exprListDeleteNN(sqlite3
*db
, ExprList
*pList
){
2228 int i
= pList
->nExpr
;
2229 struct ExprList_item
*pItem
= pList
->a
;
2230 assert( pList
->nExpr
>0 );
2233 sqlite3ExprDelete(db
, pItem
->pExpr
);
2234 if( pItem
->zEName
) sqlite3DbNNFreeNN(db
, pItem
->zEName
);
2237 sqlite3DbNNFreeNN(db
, pList
);
2239 void sqlite3ExprListDelete(sqlite3
*db
, ExprList
*pList
){
2240 if( pList
) exprListDeleteNN(db
, pList
);
2244 ** Return the bitwise-OR of all Expr.flags fields in the given
2247 u32
sqlite3ExprListFlags(const ExprList
*pList
){
2251 for(i
=0; i
<pList
->nExpr
; i
++){
2252 Expr
*pExpr
= pList
->a
[i
].pExpr
;
2260 ** This is a SELECT-node callback for the expression walker that
2261 ** always "fails". By "fail" in this case, we mean set
2262 ** pWalker->eCode to zero and abort.
2264 ** This callback is used by multiple expression walkers.
2266 int sqlite3SelectWalkFail(Walker
*pWalker
, Select
*NotUsed
){
2267 UNUSED_PARAMETER(NotUsed
);
2273 ** Check the input string to see if it is "true" or "false" (in any case).
2275 ** If the string is.... Return
2277 ** "false" EP_IsFalse
2280 u32
sqlite3IsTrueOrFalse(const char *zIn
){
2281 if( sqlite3StrICmp(zIn
, "true")==0 ) return EP_IsTrue
;
2282 if( sqlite3StrICmp(zIn
, "false")==0 ) return EP_IsFalse
;
2288 ** If the input expression is an ID with the name "true" or "false"
2289 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2290 ** the conversion happened, and zero if the expression is unaltered.
2292 int sqlite3ExprIdToTrueFalse(Expr
*pExpr
){
2294 assert( pExpr
->op
==TK_ID
|| pExpr
->op
==TK_STRING
);
2295 if( !ExprHasProperty(pExpr
, EP_Quoted
|EP_IntValue
)
2296 && (v
= sqlite3IsTrueOrFalse(pExpr
->u
.zToken
))!=0
2298 pExpr
->op
= TK_TRUEFALSE
;
2299 ExprSetProperty(pExpr
, v
);
2306 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2307 ** and 0 if it is FALSE.
2309 int sqlite3ExprTruthValue(const Expr
*pExpr
){
2310 pExpr
= sqlite3ExprSkipCollateAndLikely((Expr
*)pExpr
);
2311 assert( pExpr
->op
==TK_TRUEFALSE
);
2312 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
2313 assert( sqlite3StrICmp(pExpr
->u
.zToken
,"true")==0
2314 || sqlite3StrICmp(pExpr
->u
.zToken
,"false")==0 );
2315 return pExpr
->u
.zToken
[4]==0;
2319 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2320 ** terms that are always true or false. Return the simplified expression.
2321 ** Or return the original expression if no simplification is possible.
2325 ** (x<10) AND true => (x<10)
2326 ** (x<10) AND false => false
2327 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2328 ** (x<10) AND (y=22 OR true) => (x<10)
2329 ** (y=22) OR true => true
2331 Expr
*sqlite3ExprSimplifiedAndOr(Expr
*pExpr
){
2333 if( pExpr
->op
==TK_AND
|| pExpr
->op
==TK_OR
){
2334 Expr
*pRight
= sqlite3ExprSimplifiedAndOr(pExpr
->pRight
);
2335 Expr
*pLeft
= sqlite3ExprSimplifiedAndOr(pExpr
->pLeft
);
2336 if( ExprAlwaysTrue(pLeft
) || ExprAlwaysFalse(pRight
) ){
2337 pExpr
= pExpr
->op
==TK_AND
? pRight
: pLeft
;
2338 }else if( ExprAlwaysTrue(pRight
) || ExprAlwaysFalse(pLeft
) ){
2339 pExpr
= pExpr
->op
==TK_AND
? pLeft
: pRight
;
2347 ** These routines are Walker callbacks used to check expressions to
2348 ** see if they are "constant" for some definition of constant. The
2349 ** Walker.eCode value determines the type of "constant" we are looking
2352 ** These callback routines are used to implement the following:
2354 ** sqlite3ExprIsConstant() pWalker->eCode==1
2355 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2356 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2357 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2359 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2360 ** is found to not be a constant.
2362 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2363 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2364 ** when parsing an existing schema out of the sqlite_schema table and 4
2365 ** when processing a new CREATE TABLE statement. A bound parameter raises
2366 ** an error for new statements, but is silently converted
2367 ** to NULL for existing schemas. This allows sqlite_schema tables that
2368 ** contain a bound parameter because they were generated by older versions
2369 ** of SQLite to be parsed by newer versions of SQLite without raising a
2370 ** malformed schema error.
2372 static int exprNodeIsConstant(Walker
*pWalker
, Expr
*pExpr
){
2374 /* If pWalker->eCode is 2 then any term of the expression that comes from
2375 ** the ON or USING clauses of an outer join disqualifies the expression
2376 ** from being considered constant. */
2377 if( pWalker
->eCode
==2 && ExprHasProperty(pExpr
, EP_OuterON
) ){
2382 switch( pExpr
->op
){
2383 /* Consider functions to be constant if all their arguments are constant
2384 ** and either pWalker->eCode==4 or 5 or the function has the
2385 ** SQLITE_FUNC_CONST flag. */
2387 if( (pWalker
->eCode
>=4 || ExprHasProperty(pExpr
,EP_ConstFunc
))
2388 && !ExprHasProperty(pExpr
, EP_WinFunc
)
2390 if( pWalker
->eCode
==5 ) ExprSetProperty(pExpr
, EP_FromDDL
);
2391 return WRC_Continue
;
2397 /* Convert "true" or "false" in a DEFAULT clause into the
2398 ** appropriate TK_TRUEFALSE operator */
2399 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
2402 /* no break */ deliberate_fall_through
2404 case TK_AGG_FUNCTION
:
2406 testcase( pExpr
->op
==TK_ID
);
2407 testcase( pExpr
->op
==TK_COLUMN
);
2408 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
2409 testcase( pExpr
->op
==TK_AGG_COLUMN
);
2410 if( ExprHasProperty(pExpr
, EP_FixedCol
) && pWalker
->eCode
!=2 ){
2411 return WRC_Continue
;
2413 if( pWalker
->eCode
==3 && pExpr
->iTable
==pWalker
->u
.iCur
){
2414 return WRC_Continue
;
2416 /* no break */ deliberate_fall_through
2417 case TK_IF_NULL_ROW
:
2420 testcase( pExpr
->op
==TK_REGISTER
);
2421 testcase( pExpr
->op
==TK_IF_NULL_ROW
);
2422 testcase( pExpr
->op
==TK_DOT
);
2426 if( pWalker
->eCode
==5 ){
2427 /* Silently convert bound parameters that appear inside of CREATE
2428 ** statements into a NULL when parsing the CREATE statement text out
2429 ** of the sqlite_schema table */
2430 pExpr
->op
= TK_NULL
;
2431 }else if( pWalker
->eCode
==4 ){
2432 /* A bound parameter in a CREATE statement that originates from
2433 ** sqlite3_prepare() causes an error */
2437 /* no break */ deliberate_fall_through
2439 testcase( pExpr
->op
==TK_SELECT
); /* sqlite3SelectWalkFail() disallows */
2440 testcase( pExpr
->op
==TK_EXISTS
); /* sqlite3SelectWalkFail() disallows */
2441 return WRC_Continue
;
2444 static int exprIsConst(Expr
*p
, int initFlag
, int iCur
){
2447 w
.xExprCallback
= exprNodeIsConstant
;
2448 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2450 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2453 sqlite3WalkExpr(&w
, p
);
2458 ** Walk an expression tree. Return non-zero if the expression is constant
2459 ** and 0 if it involves variables or function calls.
2461 ** For the purposes of this function, a double-quoted string (ex: "abc")
2462 ** is considered a variable but a single-quoted string (ex: 'abc') is
2465 int sqlite3ExprIsConstant(Expr
*p
){
2466 return exprIsConst(p
, 1, 0);
2470 ** Walk an expression tree. Return non-zero if
2472 ** (1) the expression is constant, and
2473 ** (2) the expression does originate in the ON or USING clause
2474 ** of a LEFT JOIN, and
2475 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2476 ** operands created by the constant propagation optimization.
2478 ** When this routine returns true, it indicates that the expression
2479 ** can be added to the pParse->pConstExpr list and evaluated once when
2480 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2482 int sqlite3ExprIsConstantNotJoin(Expr
*p
){
2483 return exprIsConst(p
, 2, 0);
2487 ** Walk an expression tree. Return non-zero if the expression is constant
2488 ** for any single row of the table with cursor iCur. In other words, the
2489 ** expression must not refer to any non-deterministic function nor any
2490 ** table other than iCur.
2492 int sqlite3ExprIsTableConstant(Expr
*p
, int iCur
){
2493 return exprIsConst(p
, 3, iCur
);
2497 ** Check pExpr to see if it is an constraint on the single data source
2498 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
2499 ** constrains pSrc but does not depend on any other tables or data
2500 ** sources anywhere else in the query. Return true (non-zero) if pExpr
2501 ** is a constraint on pSrc only.
2503 ** This is an optimization. False negatives will perhaps cause slower
2504 ** queries, but false positives will yield incorrect answers. So when in
2507 ** To be an single-source constraint, the following must be true:
2509 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2511 ** (2) pExpr cannot use subqueries or non-deterministic functions.
2513 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2514 ** (Is there some way to relax this constraint?)
2516 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2517 ** (4a) pExpr must come from an ON clause..
2518 ** (4b) and specifically the ON clause associated with the LEFT JOIN.
2520 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2521 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2522 ** clause, not an ON clause.
2526 ** (6a) pExpr does not originate in an ON or USING clause, or
2528 ** (6b) The ON or USING clause from which pExpr is derived is
2529 ** not to the left of a RIGHT JOIN (or FULL JOIN).
2531 ** Without this restriction, accepting pExpr as a single-table
2532 ** constraint might move the the ON/USING filter expression
2533 ** from the left side of a RIGHT JOIN over to the right side,
2534 ** which leads to incorrect answers. See also restriction (9)
2537 int sqlite3ExprIsSingleTableConstraint(
2538 Expr
*pExpr
, /* The constraint */
2539 const SrcList
*pSrcList
, /* Complete FROM clause */
2540 int iSrc
/* Which element of pSrcList to use */
2542 const SrcItem
*pSrc
= &pSrcList
->a
[iSrc
];
2543 if( pSrc
->fg
.jointype
& JT_LTORJ
){
2544 return 0; /* rule (3) */
2546 if( pSrc
->fg
.jointype
& JT_LEFT
){
2547 if( !ExprHasProperty(pExpr
, EP_OuterON
) ) return 0; /* rule (4a) */
2548 if( pExpr
->w
.iJoin
!=pSrc
->iCursor
) return 0; /* rule (4b) */
2550 if( ExprHasProperty(pExpr
, EP_OuterON
) ) return 0; /* rule (5) */
2552 if( ExprHasProperty(pExpr
, EP_OuterON
|EP_InnerON
) /* (6a) */
2553 && (pSrcList
->a
[0].fg
.jointype
& JT_LTORJ
)!=0 /* Fast pre-test of (6b) */
2556 for(jj
=0; jj
<iSrc
; jj
++){
2557 if( pExpr
->w
.iJoin
==pSrcList
->a
[jj
].iCursor
){
2558 if( (pSrcList
->a
[jj
].fg
.jointype
& JT_LTORJ
)!=0 ){
2559 return 0; /* restriction (6) */
2565 return sqlite3ExprIsTableConstant(pExpr
, pSrc
->iCursor
); /* rules (1), (2) */
2570 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2572 static int exprNodeIsConstantOrGroupBy(Walker
*pWalker
, Expr
*pExpr
){
2573 ExprList
*pGroupBy
= pWalker
->u
.pGroupBy
;
2576 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2578 for(i
=0; i
<pGroupBy
->nExpr
; i
++){
2579 Expr
*p
= pGroupBy
->a
[i
].pExpr
;
2580 if( sqlite3ExprCompare(0, pExpr
, p
, -1)<2 ){
2581 CollSeq
*pColl
= sqlite3ExprNNCollSeq(pWalker
->pParse
, p
);
2582 if( sqlite3IsBinary(pColl
) ){
2588 /* Check if pExpr is a sub-select. If so, consider it variable. */
2589 if( ExprUseXSelect(pExpr
) ){
2594 return exprNodeIsConstant(pWalker
, pExpr
);
2598 ** Walk the expression tree passed as the first argument. Return non-zero
2599 ** if the expression consists entirely of constants or copies of terms
2600 ** in pGroupBy that sort with the BINARY collation sequence.
2602 ** This routine is used to determine if a term of the HAVING clause can
2603 ** be promoted into the WHERE clause. In order for such a promotion to work,
2604 ** the value of the HAVING clause term must be the same for all members of
2605 ** a "group". The requirement that the GROUP BY term must be BINARY
2606 ** assumes that no other collating sequence will have a finer-grained
2607 ** grouping than binary. In other words (A=B COLLATE binary) implies
2608 ** A=B in every other collating sequence. The requirement that the
2609 ** GROUP BY be BINARY is stricter than necessary. It would also work
2610 ** to promote HAVING clauses that use the same alternative collating
2611 ** sequence as the GROUP BY term, but that is much harder to check,
2612 ** alternative collating sequences are uncommon, and this is only an
2613 ** optimization, so we take the easy way out and simply require the
2614 ** GROUP BY to use the BINARY collating sequence.
2616 int sqlite3ExprIsConstantOrGroupBy(Parse
*pParse
, Expr
*p
, ExprList
*pGroupBy
){
2619 w
.xExprCallback
= exprNodeIsConstantOrGroupBy
;
2620 w
.xSelectCallback
= 0;
2621 w
.u
.pGroupBy
= pGroupBy
;
2623 sqlite3WalkExpr(&w
, p
);
2628 ** Walk an expression tree for the DEFAULT field of a column definition
2629 ** in a CREATE TABLE statement. Return non-zero if the expression is
2630 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2631 ** the expression is constant or a function call with constant arguments.
2632 ** Return and 0 if there are any variables.
2634 ** isInit is true when parsing from sqlite_schema. isInit is false when
2635 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2636 ** (such as ? or $abc) in the expression are converted into NULL. When
2637 ** isInit is false, parameters raise an error. Parameters should not be
2638 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2639 ** allowed it, so we need to support it when reading sqlite_schema for
2640 ** backwards compatibility.
2642 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2644 ** For the purposes of this function, a double-quoted string (ex: "abc")
2645 ** is considered a variable but a single-quoted string (ex: 'abc') is
2648 int sqlite3ExprIsConstantOrFunction(Expr
*p
, u8 isInit
){
2649 assert( isInit
==0 || isInit
==1 );
2650 return exprIsConst(p
, 4+isInit
, 0);
2653 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2655 ** Walk an expression tree. Return 1 if the expression contains a
2656 ** subquery of some kind. Return 0 if there are no subqueries.
2658 int sqlite3ExprContainsSubquery(Expr
*p
){
2661 w
.xExprCallback
= sqlite3ExprWalkNoop
;
2662 w
.xSelectCallback
= sqlite3SelectWalkFail
;
2664 w
.xSelectCallback2
= sqlite3SelectWalkAssert2
;
2666 sqlite3WalkExpr(&w
, p
);
2672 ** If the expression p codes a constant integer that is small enough
2673 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2674 ** in *pValue. If the expression is not an integer or if it is too big
2675 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2677 int sqlite3ExprIsInteger(const Expr
*p
, int *pValue
){
2679 if( NEVER(p
==0) ) return 0; /* Used to only happen following on OOM */
2681 /* If an expression is an integer literal that fits in a signed 32-bit
2682 ** integer, then the EP_IntValue flag will have already been set */
2683 assert( p
->op
!=TK_INTEGER
|| (p
->flags
& EP_IntValue
)!=0
2684 || sqlite3GetInt32(p
->u
.zToken
, &rc
)==0 );
2686 if( p
->flags
& EP_IntValue
){
2687 *pValue
= p
->u
.iValue
;
2692 rc
= sqlite3ExprIsInteger(p
->pLeft
, pValue
);
2697 if( sqlite3ExprIsInteger(p
->pLeft
, &v
) ){
2698 assert( ((unsigned int)v
)!=0x80000000 );
2710 ** Return FALSE if there is no chance that the expression can be NULL.
2712 ** If the expression might be NULL or if the expression is too complex
2713 ** to tell return TRUE.
2715 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2716 ** when we know that a value cannot be NULL. Hence, a false positive
2717 ** (returning TRUE when in fact the expression can never be NULL) might
2718 ** be a small performance hit but is otherwise harmless. On the other
2719 ** hand, a false negative (returning FALSE when the result could be NULL)
2720 ** will likely result in an incorrect answer. So when in doubt, return
2723 int sqlite3ExprCanBeNull(const Expr
*p
){
2726 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){
2731 if( op
==TK_REGISTER
) op
= p
->op2
;
2739 assert( ExprUseYTab(p
) );
2740 return ExprHasProperty(p
, EP_CanBeNull
) ||
2741 p
->y
.pTab
==0 || /* Reference to column of index on expression */
2743 && p
->y
.pTab
->aCol
!=0 /* Possible due to prior error */
2744 && p
->y
.pTab
->aCol
[p
->iColumn
].notNull
==0);
2751 ** Return TRUE if the given expression is a constant which would be
2752 ** unchanged by OP_Affinity with the affinity given in the second
2755 ** This routine is used to determine if the OP_Affinity operation
2756 ** can be omitted. When in doubt return FALSE. A false negative
2757 ** is harmless. A false positive, however, can result in the wrong
2760 int sqlite3ExprNeedsNoAffinityChange(const Expr
*p
, char aff
){
2763 if( aff
==SQLITE_AFF_BLOB
) return 1;
2764 while( p
->op
==TK_UPLUS
|| p
->op
==TK_UMINUS
){
2765 if( p
->op
==TK_UMINUS
) unaryMinus
= 1;
2769 if( op
==TK_REGISTER
) op
= p
->op2
;
2772 return aff
>=SQLITE_AFF_NUMERIC
;
2775 return aff
>=SQLITE_AFF_NUMERIC
;
2778 return !unaryMinus
&& aff
==SQLITE_AFF_TEXT
;
2784 assert( p
->iTable
>=0 ); /* p cannot be part of a CHECK constraint */
2785 return aff
>=SQLITE_AFF_NUMERIC
&& p
->iColumn
<0;
2794 ** Return TRUE if the given string is a row-id column name.
2796 int sqlite3IsRowid(const char *z
){
2797 if( sqlite3StrICmp(z
, "_ROWID_")==0 ) return 1;
2798 if( sqlite3StrICmp(z
, "ROWID")==0 ) return 1;
2799 if( sqlite3StrICmp(z
, "OID")==0 ) return 1;
2804 ** Return a pointer to a buffer containing a usable rowid alias for table
2805 ** pTab. An alias is usable if there is not an explicit user-defined column
2806 ** of the same name.
2808 const char *sqlite3RowidAlias(Table
*pTab
){
2809 const char *azOpt
[] = {"_ROWID_", "ROWID", "OID"};
2811 assert( VisibleRowid(pTab
) );
2812 for(ii
=0; ii
<ArraySize(azOpt
); ii
++){
2814 for(iCol
=0; iCol
<pTab
->nCol
; iCol
++){
2815 if( sqlite3_stricmp(azOpt
[ii
], pTab
->aCol
[iCol
].zCnName
)==0 ) break;
2817 if( iCol
==pTab
->nCol
){
2825 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2826 ** that can be simplified to a direct table access, then return
2827 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2828 ** or if the SELECT statement needs to be materialized into a transient
2829 ** table, then return NULL.
2831 #ifndef SQLITE_OMIT_SUBQUERY
2832 static Select
*isCandidateForInOpt(const Expr
*pX
){
2838 if( !ExprUseXSelect(pX
) ) return 0; /* Not a subquery */
2839 if( ExprHasProperty(pX
, EP_VarSelect
) ) return 0; /* Correlated subq */
2841 if( p
->pPrior
) return 0; /* Not a compound SELECT */
2842 if( p
->selFlags
& (SF_Distinct
|SF_Aggregate
) ){
2843 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Distinct
);
2844 testcase( (p
->selFlags
& (SF_Distinct
|SF_Aggregate
))==SF_Aggregate
);
2845 return 0; /* No DISTINCT keyword and no aggregate functions */
2847 assert( p
->pGroupBy
==0 ); /* Has no GROUP BY clause */
2848 if( p
->pLimit
) return 0; /* Has no LIMIT clause */
2849 if( p
->pWhere
) return 0; /* Has no WHERE clause */
2852 if( pSrc
->nSrc
!=1 ) return 0; /* Single term in FROM clause */
2853 if( pSrc
->a
[0].pSelect
) return 0; /* FROM is not a subquery or view */
2854 pTab
= pSrc
->a
[0].pTab
;
2856 assert( !IsView(pTab
) ); /* FROM clause is not a view */
2857 if( IsVirtual(pTab
) ) return 0; /* FROM clause not a virtual table */
2859 assert( pEList
!=0 );
2860 /* All SELECT results must be columns. */
2861 for(i
=0; i
<pEList
->nExpr
; i
++){
2862 Expr
*pRes
= pEList
->a
[i
].pExpr
;
2863 if( pRes
->op
!=TK_COLUMN
) return 0;
2864 assert( pRes
->iTable
==pSrc
->a
[0].iCursor
); /* Not a correlated subquery */
2868 #endif /* SQLITE_OMIT_SUBQUERY */
2870 #ifndef SQLITE_OMIT_SUBQUERY
2872 ** Generate code that checks the left-most column of index table iCur to see if
2873 ** it contains any NULL entries. Cause the register at regHasNull to be set
2874 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2875 ** to be set to NULL if iCur contains one or more NULL values.
2877 static void sqlite3SetHasNullFlag(Vdbe
*v
, int iCur
, int regHasNull
){
2879 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, regHasNull
);
2880 addr1
= sqlite3VdbeAddOp1(v
, OP_Rewind
, iCur
); VdbeCoverage(v
);
2881 sqlite3VdbeAddOp3(v
, OP_Column
, iCur
, 0, regHasNull
);
2882 sqlite3VdbeChangeP5(v
, OPFLAG_TYPEOFARG
);
2883 VdbeComment((v
, "first_entry_in(%d)", iCur
));
2884 sqlite3VdbeJumpHere(v
, addr1
);
2889 #ifndef SQLITE_OMIT_SUBQUERY
2891 ** The argument is an IN operator with a list (not a subquery) on the
2892 ** right-hand side. Return TRUE if that list is constant.
2894 static int sqlite3InRhsIsConstant(Expr
*pIn
){
2897 assert( !ExprHasProperty(pIn
, EP_xIsSelect
) );
2900 res
= sqlite3ExprIsConstant(pIn
);
2907 ** This function is used by the implementation of the IN (...) operator.
2908 ** The pX parameter is the expression on the RHS of the IN operator, which
2909 ** might be either a list of expressions or a subquery.
2911 ** The job of this routine is to find or create a b-tree object that can
2912 ** be used either to test for membership in the RHS set or to iterate through
2913 ** all members of the RHS set, skipping duplicates.
2915 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2916 ** and the *piTab parameter is set to the index of that cursor.
2918 ** The returned value of this function indicates the b-tree type, as follows:
2920 ** IN_INDEX_ROWID - The cursor was opened on a database table.
2921 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2922 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2923 ** IN_INDEX_EPH - The cursor was opened on a specially created and
2924 ** populated ephemeral table.
2925 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2926 ** implemented as a sequence of comparisons.
2928 ** An existing b-tree might be used if the RHS expression pX is a simple
2929 ** subquery such as:
2931 ** SELECT <column1>, <column2>... FROM <table>
2933 ** If the RHS of the IN operator is a list or a more complex subquery, then
2934 ** an ephemeral table might need to be generated from the RHS and then
2935 ** pX->iTable made to point to the ephemeral table instead of an
2936 ** existing table. In this case, the creation and initialization of the
2937 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag
2938 ** will be set on pX and the pX->y.sub fields will be set to show where
2939 ** the subroutine is coded.
2941 ** The inFlags parameter must contain, at a minimum, one of the bits
2942 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2943 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2944 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2945 ** be used to loop over all values of the RHS of the IN operator.
2947 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2948 ** through the set members) then the b-tree must not contain duplicates.
2949 ** An ephemeral table will be created unless the selected columns are guaranteed
2950 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2951 ** a UNIQUE constraint or index.
2953 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2954 ** for fast set membership tests) then an ephemeral table must
2955 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2956 ** index can be found with the specified <columns> as its left-most.
2958 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2959 ** if the RHS of the IN operator is a list (not a subquery) then this
2960 ** routine might decide that creating an ephemeral b-tree for membership
2961 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2962 ** calling routine should implement the IN operator using a sequence
2963 ** of Eq or Ne comparison operations.
2965 ** When the b-tree is being used for membership tests, the calling function
2966 ** might need to know whether or not the RHS side of the IN operator
2967 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
2968 ** if there is any chance that the (...) might contain a NULL value at
2969 ** runtime, then a register is allocated and the register number written
2970 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2971 ** NULL value, then *prRhsHasNull is left unchanged.
2973 ** If a register is allocated and its location stored in *prRhsHasNull, then
2974 ** the value in that register will be NULL if the b-tree contains one or more
2975 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2978 ** If the aiMap parameter is not NULL, it must point to an array containing
2979 ** one element for each column returned by the SELECT statement on the RHS
2980 ** of the IN(...) operator. The i'th entry of the array is populated with the
2981 ** offset of the index column that matches the i'th column returned by the
2982 ** SELECT. For example, if the expression and selected index are:
2984 ** (?,?,?) IN (SELECT a, b, c FROM t1)
2985 ** CREATE INDEX i1 ON t1(b, c, a);
2987 ** then aiMap[] is populated with {2, 0, 1}.
2989 #ifndef SQLITE_OMIT_SUBQUERY
2990 int sqlite3FindInIndex(
2991 Parse
*pParse
, /* Parsing context */
2992 Expr
*pX
, /* The IN expression */
2993 u32 inFlags
, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2994 int *prRhsHasNull
, /* Register holding NULL status. See notes */
2995 int *aiMap
, /* Mapping from Index fields to RHS fields */
2996 int *piTab
/* OUT: index to use */
2998 Select
*p
; /* SELECT to the right of IN operator */
2999 int eType
= 0; /* Type of RHS table. IN_INDEX_* */
3000 int iTab
; /* Cursor of the RHS table */
3001 int mustBeUnique
; /* True if RHS must be unique */
3002 Vdbe
*v
= sqlite3GetVdbe(pParse
); /* Virtual machine being coded */
3004 assert( pX
->op
==TK_IN
);
3005 mustBeUnique
= (inFlags
& IN_INDEX_LOOP
)!=0;
3006 iTab
= pParse
->nTab
++;
3008 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
3009 ** whether or not the SELECT result contains NULL values, check whether
3010 ** or not NULL is actually possible (it may not be, for example, due
3011 ** to NOT NULL constraints in the schema). If no NULL values are possible,
3012 ** set prRhsHasNull to 0 before continuing. */
3013 if( prRhsHasNull
&& ExprUseXSelect(pX
) ){
3015 ExprList
*pEList
= pX
->x
.pSelect
->pEList
;
3016 for(i
=0; i
<pEList
->nExpr
; i
++){
3017 if( sqlite3ExprCanBeNull(pEList
->a
[i
].pExpr
) ) break;
3019 if( i
==pEList
->nExpr
){
3024 /* Check to see if an existing table or index can be used to
3025 ** satisfy the query. This is preferable to generating a new
3026 ** ephemeral table. */
3027 if( pParse
->nErr
==0 && (p
= isCandidateForInOpt(pX
))!=0 ){
3028 sqlite3
*db
= pParse
->db
; /* Database connection */
3029 Table
*pTab
; /* Table <table>. */
3030 int iDb
; /* Database idx for pTab */
3031 ExprList
*pEList
= p
->pEList
;
3032 int nExpr
= pEList
->nExpr
;
3034 assert( p
->pEList
!=0 ); /* Because of isCandidateForInOpt(p) */
3035 assert( p
->pEList
->a
[0].pExpr
!=0 ); /* Because of isCandidateForInOpt(p) */
3036 assert( p
->pSrc
!=0 ); /* Because of isCandidateForInOpt(p) */
3037 pTab
= p
->pSrc
->a
[0].pTab
;
3039 /* Code an OP_Transaction and OP_TableLock for <table>. */
3040 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
3041 assert( iDb
>=0 && iDb
<SQLITE_MAX_DB
);
3042 sqlite3CodeVerifySchema(pParse
, iDb
);
3043 sqlite3TableLock(pParse
, iDb
, pTab
->tnum
, 0, pTab
->zName
);
3045 assert(v
); /* sqlite3GetVdbe() has always been previously called */
3046 if( nExpr
==1 && pEList
->a
[0].pExpr
->iColumn
<0 ){
3047 /* The "x IN (SELECT rowid FROM table)" case */
3048 int iAddr
= sqlite3VdbeAddOp0(v
, OP_Once
);
3051 sqlite3OpenTable(pParse
, iTab
, iDb
, pTab
, OP_OpenRead
);
3052 eType
= IN_INDEX_ROWID
;
3053 ExplainQueryPlan((pParse
, 0,
3054 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab
->zName
));
3055 sqlite3VdbeJumpHere(v
, iAddr
);
3057 Index
*pIdx
; /* Iterator variable */
3058 int affinity_ok
= 1;
3061 /* Check that the affinity that will be used to perform each
3062 ** comparison is the same as the affinity of each column in table
3063 ** on the RHS of the IN operator. If it not, it is not possible to
3064 ** use any index of the RHS table. */
3065 for(i
=0; i
<nExpr
&& affinity_ok
; i
++){
3066 Expr
*pLhs
= sqlite3VectorFieldSubexpr(pX
->pLeft
, i
);
3067 int iCol
= pEList
->a
[i
].pExpr
->iColumn
;
3068 char idxaff
= sqlite3TableColumnAffinity(pTab
,iCol
); /* RHS table */
3069 char cmpaff
= sqlite3CompareAffinity(pLhs
, idxaff
);
3070 testcase( cmpaff
==SQLITE_AFF_BLOB
);
3071 testcase( cmpaff
==SQLITE_AFF_TEXT
);
3073 case SQLITE_AFF_BLOB
:
3075 case SQLITE_AFF_TEXT
:
3076 /* sqlite3CompareAffinity() only returns TEXT if one side or the
3077 ** other has no affinity and the other side is TEXT. Hence,
3078 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
3079 ** and for the term on the LHS of the IN to have no affinity. */
3080 assert( idxaff
==SQLITE_AFF_TEXT
);
3083 affinity_ok
= sqlite3IsNumericAffinity(idxaff
);
3088 /* Search for an existing index that will work for this IN operator */
3089 for(pIdx
=pTab
->pIndex
; pIdx
&& eType
==0; pIdx
=pIdx
->pNext
){
3090 Bitmask colUsed
; /* Columns of the index used */
3091 Bitmask mCol
; /* Mask for the current column */
3092 if( pIdx
->nColumn
<nExpr
) continue;
3093 if( pIdx
->pPartIdxWhere
!=0 ) continue;
3094 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
3095 ** BITMASK(nExpr) without overflowing */
3096 testcase( pIdx
->nColumn
==BMS
-2 );
3097 testcase( pIdx
->nColumn
==BMS
-1 );
3098 if( pIdx
->nColumn
>=BMS
-1 ) continue;
3100 if( pIdx
->nKeyCol
>nExpr
3101 ||(pIdx
->nColumn
>nExpr
&& !IsUniqueIndex(pIdx
))
3103 continue; /* This index is not unique over the IN RHS columns */
3107 colUsed
= 0; /* Columns of index used so far */
3108 for(i
=0; i
<nExpr
; i
++){
3109 Expr
*pLhs
= sqlite3VectorFieldSubexpr(pX
->pLeft
, i
);
3110 Expr
*pRhs
= pEList
->a
[i
].pExpr
;
3111 CollSeq
*pReq
= sqlite3BinaryCompareCollSeq(pParse
, pLhs
, pRhs
);
3114 for(j
=0; j
<nExpr
; j
++){
3115 if( pIdx
->aiColumn
[j
]!=pRhs
->iColumn
) continue;
3116 assert( pIdx
->azColl
[j
] );
3117 if( pReq
!=0 && sqlite3StrICmp(pReq
->zName
, pIdx
->azColl
[j
])!=0 ){
3122 if( j
==nExpr
) break;
3124 if( mCol
& colUsed
) break; /* Each column used only once */
3126 if( aiMap
) aiMap
[i
] = j
;
3129 assert( i
==nExpr
|| colUsed
!=(MASKBIT(nExpr
)-1) );
3130 if( colUsed
==(MASKBIT(nExpr
)-1) ){
3131 /* If we reach this point, that means the index pIdx is usable */
3132 int iAddr
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3133 ExplainQueryPlan((pParse
, 0,
3134 "USING INDEX %s FOR IN-OPERATOR",pIdx
->zName
));
3135 sqlite3VdbeAddOp3(v
, OP_OpenRead
, iTab
, pIdx
->tnum
, iDb
);
3136 sqlite3VdbeSetP4KeyInfo(pParse
, pIdx
);
3137 VdbeComment((v
, "%s", pIdx
->zName
));
3138 assert( IN_INDEX_INDEX_DESC
== IN_INDEX_INDEX_ASC
+1 );
3139 eType
= IN_INDEX_INDEX_ASC
+ pIdx
->aSortOrder
[0];
3142 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3143 i64 mask
= (1<<nExpr
)-1;
3144 sqlite3VdbeAddOp4Dup8(v
, OP_ColumnsUsed
,
3145 iTab
, 0, 0, (u8
*)&mask
, P4_INT64
);
3147 *prRhsHasNull
= ++pParse
->nMem
;
3149 sqlite3SetHasNullFlag(v
, iTab
, *prRhsHasNull
);
3152 sqlite3VdbeJumpHere(v
, iAddr
);
3154 } /* End loop over indexes */
3155 } /* End if( affinity_ok ) */
3156 } /* End if not an rowid index */
3157 } /* End attempt to optimize using an index */
3159 /* If no preexisting index is available for the IN clause
3160 ** and IN_INDEX_NOOP is an allowed reply
3161 ** and the RHS of the IN operator is a list, not a subquery
3162 ** and the RHS is not constant or has two or fewer terms,
3163 ** then it is not worth creating an ephemeral table to evaluate
3164 ** the IN operator so return IN_INDEX_NOOP.
3167 && (inFlags
& IN_INDEX_NOOP_OK
)
3169 && (!sqlite3InRhsIsConstant(pX
) || pX
->x
.pList
->nExpr
<=2)
3171 pParse
->nTab
--; /* Back out the allocation of the unused cursor */
3172 iTab
= -1; /* Cursor is not allocated */
3173 eType
= IN_INDEX_NOOP
;
3177 /* Could not find an existing table or index to use as the RHS b-tree.
3178 ** We will have to generate an ephemeral table to do the job.
3180 u32 savedNQueryLoop
= pParse
->nQueryLoop
;
3181 int rMayHaveNull
= 0;
3182 eType
= IN_INDEX_EPH
;
3183 if( inFlags
& IN_INDEX_LOOP
){
3184 pParse
->nQueryLoop
= 0;
3185 }else if( prRhsHasNull
){
3186 *prRhsHasNull
= rMayHaveNull
= ++pParse
->nMem
;
3188 assert( pX
->op
==TK_IN
);
3189 sqlite3CodeRhsOfIN(pParse
, pX
, iTab
);
3191 sqlite3SetHasNullFlag(v
, iTab
, rMayHaveNull
);
3193 pParse
->nQueryLoop
= savedNQueryLoop
;
3196 if( aiMap
&& eType
!=IN_INDEX_INDEX_ASC
&& eType
!=IN_INDEX_INDEX_DESC
){
3198 n
= sqlite3ExprVectorSize(pX
->pLeft
);
3199 for(i
=0; i
<n
; i
++) aiMap
[i
] = i
;
3206 #ifndef SQLITE_OMIT_SUBQUERY
3208 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3209 ** function allocates and returns a nul-terminated string containing
3210 ** the affinities to be used for each column of the comparison.
3212 ** It is the responsibility of the caller to ensure that the returned
3213 ** string is eventually freed using sqlite3DbFree().
3215 static char *exprINAffinity(Parse
*pParse
, const Expr
*pExpr
){
3216 Expr
*pLeft
= pExpr
->pLeft
;
3217 int nVal
= sqlite3ExprVectorSize(pLeft
);
3218 Select
*pSelect
= ExprUseXSelect(pExpr
) ? pExpr
->x
.pSelect
: 0;
3221 assert( pExpr
->op
==TK_IN
);
3222 zRet
= sqlite3DbMallocRaw(pParse
->db
, nVal
+1);
3225 for(i
=0; i
<nVal
; i
++){
3226 Expr
*pA
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3227 char a
= sqlite3ExprAffinity(pA
);
3229 zRet
[i
] = sqlite3CompareAffinity(pSelect
->pEList
->a
[i
].pExpr
, a
);
3240 #ifndef SQLITE_OMIT_SUBQUERY
3242 ** Load the Parse object passed as the first argument with an error
3243 ** message of the form:
3245 ** "sub-select returns N columns - expected M"
3247 void sqlite3SubselectError(Parse
*pParse
, int nActual
, int nExpect
){
3248 if( pParse
->nErr
==0 ){
3249 const char *zFmt
= "sub-select returns %d columns - expected %d";
3250 sqlite3ErrorMsg(pParse
, zFmt
, nActual
, nExpect
);
3256 ** Expression pExpr is a vector that has been used in a context where
3257 ** it is not permitted. If pExpr is a sub-select vector, this routine
3258 ** loads the Parse object with a message of the form:
3260 ** "sub-select returns N columns - expected 1"
3262 ** Or, if it is a regular scalar vector:
3264 ** "row value misused"
3266 void sqlite3VectorErrorMsg(Parse
*pParse
, Expr
*pExpr
){
3267 #ifndef SQLITE_OMIT_SUBQUERY
3268 if( ExprUseXSelect(pExpr
) ){
3269 sqlite3SubselectError(pParse
, pExpr
->x
.pSelect
->pEList
->nExpr
, 1);
3273 sqlite3ErrorMsg(pParse
, "row value misused");
3277 #ifndef SQLITE_OMIT_SUBQUERY
3279 ** Generate code that will construct an ephemeral table containing all terms
3280 ** in the RHS of an IN operator. The IN operator can be in either of two
3283 ** x IN (4,5,11) -- IN operator with list on right-hand side
3284 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3286 ** The pExpr parameter is the IN operator. The cursor number for the
3287 ** constructed ephemeral table is returned. The first time the ephemeral
3288 ** table is computed, the cursor number is also stored in pExpr->iTable,
3289 ** however the cursor number returned might not be the same, as it might
3290 ** have been duplicated using OP_OpenDup.
3292 ** If the LHS expression ("x" in the examples) is a column value, or
3293 ** the SELECT statement returns a column value, then the affinity of that
3294 ** column is used to build the index keys. If both 'x' and the
3295 ** SELECT... statement are columns, then numeric affinity is used
3296 ** if either column has NUMERIC or INTEGER affinity. If neither
3297 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3300 void sqlite3CodeRhsOfIN(
3301 Parse
*pParse
, /* Parsing context */
3302 Expr
*pExpr
, /* The IN operator */
3303 int iTab
/* Use this cursor number */
3305 int addrOnce
= 0; /* Address of the OP_Once instruction at top */
3306 int addr
; /* Address of OP_OpenEphemeral instruction */
3307 Expr
*pLeft
; /* the LHS of the IN operator */
3308 KeyInfo
*pKeyInfo
= 0; /* Key information */
3309 int nVal
; /* Size of vector pLeft */
3310 Vdbe
*v
; /* The prepared statement under construction */
3315 /* The evaluation of the IN must be repeated every time it
3316 ** is encountered if any of the following is true:
3318 ** * The right-hand side is a correlated subquery
3319 ** * The right-hand side is an expression list containing variables
3320 ** * We are inside a trigger
3322 ** If all of the above are false, then we can compute the RHS just once
3323 ** and reuse it many names.
3325 if( !ExprHasProperty(pExpr
, EP_VarSelect
) && pParse
->iSelfTab
==0 ){
3326 /* Reuse of the RHS is allowed */
3327 /* If this routine has already been coded, but the previous code
3328 ** might not have been invoked yet, so invoke it now as a subroutine.
3330 if( ExprHasProperty(pExpr
, EP_Subrtn
) ){
3331 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3332 if( ExprUseXSelect(pExpr
) ){
3333 ExplainQueryPlan((pParse
, 0, "REUSE LIST SUBQUERY %d",
3334 pExpr
->x
.pSelect
->selId
));
3336 assert( ExprUseYSub(pExpr
) );
3337 sqlite3VdbeAddOp2(v
, OP_Gosub
, pExpr
->y
.sub
.regReturn
,
3338 pExpr
->y
.sub
.iAddr
);
3339 assert( iTab
!=pExpr
->iTable
);
3340 sqlite3VdbeAddOp2(v
, OP_OpenDup
, iTab
, pExpr
->iTable
);
3341 sqlite3VdbeJumpHere(v
, addrOnce
);
3345 /* Begin coding the subroutine */
3346 assert( !ExprUseYWin(pExpr
) );
3347 ExprSetProperty(pExpr
, EP_Subrtn
);
3348 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
3349 pExpr
->y
.sub
.regReturn
= ++pParse
->nMem
;
3350 pExpr
->y
.sub
.iAddr
=
3351 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pExpr
->y
.sub
.regReturn
) + 1;
3353 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3356 /* Check to see if this is a vector IN operator */
3357 pLeft
= pExpr
->pLeft
;
3358 nVal
= sqlite3ExprVectorSize(pLeft
);
3360 /* Construct the ephemeral table that will contain the content of
3361 ** RHS of the IN operator.
3363 pExpr
->iTable
= iTab
;
3364 addr
= sqlite3VdbeAddOp2(v
, OP_OpenEphemeral
, pExpr
->iTable
, nVal
);
3365 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3366 if( ExprUseXSelect(pExpr
) ){
3367 VdbeComment((v
, "Result of SELECT %u", pExpr
->x
.pSelect
->selId
));
3369 VdbeComment((v
, "RHS of IN operator"));
3372 pKeyInfo
= sqlite3KeyInfoAlloc(pParse
->db
, nVal
, 1);
3374 if( ExprUseXSelect(pExpr
) ){
3375 /* Case 1: expr IN (SELECT ...)
3377 ** Generate code to write the results of the select into the temporary
3378 ** table allocated and opened above.
3380 Select
*pSelect
= pExpr
->x
.pSelect
;
3381 ExprList
*pEList
= pSelect
->pEList
;
3383 ExplainQueryPlan((pParse
, 1, "%sLIST SUBQUERY %d",
3384 addrOnce
?"":"CORRELATED ", pSelect
->selId
3386 /* If the LHS and RHS of the IN operator do not match, that
3387 ** error will have been caught long before we reach this point. */
3388 if( ALWAYS(pEList
->nExpr
==nVal
) ){
3393 sqlite3SelectDestInit(&dest
, SRT_Set
, iTab
);
3394 dest
.zAffSdst
= exprINAffinity(pParse
, pExpr
);
3395 pSelect
->iLimit
= 0;
3396 testcase( pSelect
->selFlags
& SF_Distinct
);
3397 testcase( pKeyInfo
==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3398 pCopy
= sqlite3SelectDup(pParse
->db
, pSelect
, 0);
3399 rc
= pParse
->db
->mallocFailed
? 1 :sqlite3Select(pParse
, pCopy
, &dest
);
3400 sqlite3SelectDelete(pParse
->db
, pCopy
);
3401 sqlite3DbFree(pParse
->db
, dest
.zAffSdst
);
3403 sqlite3KeyInfoUnref(pKeyInfo
);
3406 assert( pKeyInfo
!=0 ); /* OOM will cause exit after sqlite3Select() */
3407 assert( pEList
!=0 );
3408 assert( pEList
->nExpr
>0 );
3409 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
3410 for(i
=0; i
<nVal
; i
++){
3411 Expr
*p
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3412 pKeyInfo
->aColl
[i
] = sqlite3BinaryCompareCollSeq(
3413 pParse
, p
, pEList
->a
[i
].pExpr
3417 }else if( ALWAYS(pExpr
->x
.pList
!=0) ){
3418 /* Case 2: expr IN (exprlist)
3420 ** For each expression, build an index key from the evaluation and
3421 ** store it in the temporary table. If <expr> is a column, then use
3422 ** that columns affinity when building index keys. If <expr> is not
3423 ** a column, use numeric affinity.
3425 char affinity
; /* Affinity of the LHS of the IN */
3427 ExprList
*pList
= pExpr
->x
.pList
;
3428 struct ExprList_item
*pItem
;
3430 affinity
= sqlite3ExprAffinity(pLeft
);
3431 if( affinity
<=SQLITE_AFF_NONE
){
3432 affinity
= SQLITE_AFF_BLOB
;
3433 }else if( affinity
==SQLITE_AFF_REAL
){
3434 affinity
= SQLITE_AFF_NUMERIC
;
3437 assert( sqlite3KeyInfoIsWriteable(pKeyInfo
) );
3438 pKeyInfo
->aColl
[0] = sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
3441 /* Loop through each expression in <exprlist>. */
3442 r1
= sqlite3GetTempReg(pParse
);
3443 r2
= sqlite3GetTempReg(pParse
);
3444 for(i
=pList
->nExpr
, pItem
=pList
->a
; i
>0; i
--, pItem
++){
3445 Expr
*pE2
= pItem
->pExpr
;
3447 /* If the expression is not constant then we will need to
3448 ** disable the test that was generated above that makes sure
3449 ** this code only executes once. Because for a non-constant
3450 ** expression we need to rerun this code each time.
3452 if( addrOnce
&& !sqlite3ExprIsConstant(pE2
) ){
3453 sqlite3VdbeChangeToNoop(v
, addrOnce
-1);
3454 sqlite3VdbeChangeToNoop(v
, addrOnce
);
3455 ExprClearProperty(pExpr
, EP_Subrtn
);
3459 /* Evaluate the expression and insert it into the temp table */
3460 sqlite3ExprCode(pParse
, pE2
, r1
);
3461 sqlite3VdbeAddOp4(v
, OP_MakeRecord
, r1
, 1, r2
, &affinity
, 1);
3462 sqlite3VdbeAddOp4Int(v
, OP_IdxInsert
, iTab
, r2
, r1
, 1);
3464 sqlite3ReleaseTempReg(pParse
, r1
);
3465 sqlite3ReleaseTempReg(pParse
, r2
);
3468 sqlite3VdbeChangeP4(v
, addr
, (void *)pKeyInfo
, P4_KEYINFO
);
3471 sqlite3VdbeAddOp1(v
, OP_NullRow
, iTab
);
3472 sqlite3VdbeJumpHere(v
, addrOnce
);
3473 /* Subroutine return */
3474 assert( ExprUseYSub(pExpr
) );
3475 assert( sqlite3VdbeGetOp(v
,pExpr
->y
.sub
.iAddr
-1)->opcode
==OP_BeginSubrtn
3477 sqlite3VdbeAddOp3(v
, OP_Return
, pExpr
->y
.sub
.regReturn
,
3478 pExpr
->y
.sub
.iAddr
, 1);
3480 sqlite3ClearTempRegCache(pParse
);
3483 #endif /* SQLITE_OMIT_SUBQUERY */
3486 ** Generate code for scalar subqueries used as a subquery expression
3487 ** or EXISTS operator:
3489 ** (SELECT a FROM b) -- subquery
3490 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3492 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3494 ** Return the register that holds the result. For a multi-column SELECT,
3495 ** the result is stored in a contiguous array of registers and the
3496 ** return value is the register of the left-most result column.
3497 ** Return 0 if an error occurs.
3499 #ifndef SQLITE_OMIT_SUBQUERY
3500 int sqlite3CodeSubselect(Parse
*pParse
, Expr
*pExpr
){
3501 int addrOnce
= 0; /* Address of OP_Once at top of subroutine */
3502 int rReg
= 0; /* Register storing resulting */
3503 Select
*pSel
; /* SELECT statement to encode */
3504 SelectDest dest
; /* How to deal with SELECT result */
3505 int nReg
; /* Registers to allocate */
3506 Expr
*pLimit
; /* New limit expression */
3507 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3508 int addrExplain
; /* Address of OP_Explain instruction */
3511 Vdbe
*v
= pParse
->pVdbe
;
3513 if( pParse
->nErr
) return 0;
3514 testcase( pExpr
->op
==TK_EXISTS
);
3515 testcase( pExpr
->op
==TK_SELECT
);
3516 assert( pExpr
->op
==TK_EXISTS
|| pExpr
->op
==TK_SELECT
);
3517 assert( ExprUseXSelect(pExpr
) );
3518 pSel
= pExpr
->x
.pSelect
;
3520 /* If this routine has already been coded, then invoke it as a
3522 if( ExprHasProperty(pExpr
, EP_Subrtn
) ){
3523 ExplainQueryPlan((pParse
, 0, "REUSE SUBQUERY %d", pSel
->selId
));
3524 assert( ExprUseYSub(pExpr
) );
3525 sqlite3VdbeAddOp2(v
, OP_Gosub
, pExpr
->y
.sub
.regReturn
,
3526 pExpr
->y
.sub
.iAddr
);
3527 return pExpr
->iTable
;
3530 /* Begin coding the subroutine */
3531 assert( !ExprUseYWin(pExpr
) );
3532 assert( !ExprHasProperty(pExpr
, EP_Reduced
|EP_TokenOnly
) );
3533 ExprSetProperty(pExpr
, EP_Subrtn
);
3534 pExpr
->y
.sub
.regReturn
= ++pParse
->nMem
;
3535 pExpr
->y
.sub
.iAddr
=
3536 sqlite3VdbeAddOp2(v
, OP_BeginSubrtn
, 0, pExpr
->y
.sub
.regReturn
) + 1;
3538 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3539 ** is encountered if any of the following is true:
3541 ** * The right-hand side is a correlated subquery
3542 ** * The right-hand side is an expression list containing variables
3543 ** * We are inside a trigger
3545 ** If all of the above are false, then we can run this code just once
3546 ** save the results, and reuse the same result on subsequent invocations.
3548 if( !ExprHasProperty(pExpr
, EP_VarSelect
) ){
3549 addrOnce
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
3552 /* For a SELECT, generate code to put the values for all columns of
3553 ** the first row into an array of registers and return the index of
3554 ** the first register.
3556 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3557 ** into a register and return that register number.
3559 ** In both cases, the query is augmented with "LIMIT 1". Any
3560 ** preexisting limit is discarded in place of the new LIMIT 1.
3562 ExplainQueryPlan2(addrExplain
, (pParse
, 1, "%sSCALAR SUBQUERY %d",
3563 addrOnce
?"":"CORRELATED ", pSel
->selId
));
3564 sqlite3VdbeScanStatusCounters(v
, addrExplain
, addrExplain
, -1);
3565 nReg
= pExpr
->op
==TK_SELECT
? pSel
->pEList
->nExpr
: 1;
3566 sqlite3SelectDestInit(&dest
, 0, pParse
->nMem
+1);
3567 pParse
->nMem
+= nReg
;
3568 if( pExpr
->op
==TK_SELECT
){
3569 dest
.eDest
= SRT_Mem
;
3570 dest
.iSdst
= dest
.iSDParm
;
3572 sqlite3VdbeAddOp3(v
, OP_Null
, 0, dest
.iSDParm
, dest
.iSDParm
+nReg
-1);
3573 VdbeComment((v
, "Init subquery result"));
3575 dest
.eDest
= SRT_Exists
;
3576 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, dest
.iSDParm
);
3577 VdbeComment((v
, "Init EXISTS result"));
3580 /* The subquery already has a limit. If the pre-existing limit is X
3581 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3582 sqlite3
*db
= pParse
->db
;
3583 pLimit
= sqlite3Expr(db
, TK_INTEGER
, "0");
3585 pLimit
->affExpr
= SQLITE_AFF_NUMERIC
;
3586 pLimit
= sqlite3PExpr(pParse
, TK_NE
,
3587 sqlite3ExprDup(db
, pSel
->pLimit
->pLeft
, 0), pLimit
);
3589 sqlite3ExprDeferredDelete(pParse
, pSel
->pLimit
->pLeft
);
3590 pSel
->pLimit
->pLeft
= pLimit
;
3592 /* If there is no pre-existing limit add a limit of 1 */
3593 pLimit
= sqlite3Expr(pParse
->db
, TK_INTEGER
, "1");
3594 pSel
->pLimit
= sqlite3PExpr(pParse
, TK_LIMIT
, pLimit
, 0);
3597 if( sqlite3Select(pParse
, pSel
, &dest
) ){
3598 pExpr
->op2
= pExpr
->op
;
3599 pExpr
->op
= TK_ERROR
;
3602 pExpr
->iTable
= rReg
= dest
.iSDParm
;
3603 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
3605 sqlite3VdbeJumpHere(v
, addrOnce
);
3607 sqlite3VdbeScanStatusRange(v
, addrExplain
, addrExplain
, -1);
3609 /* Subroutine return */
3610 assert( ExprUseYSub(pExpr
) );
3611 assert( sqlite3VdbeGetOp(v
,pExpr
->y
.sub
.iAddr
-1)->opcode
==OP_BeginSubrtn
3613 sqlite3VdbeAddOp3(v
, OP_Return
, pExpr
->y
.sub
.regReturn
,
3614 pExpr
->y
.sub
.iAddr
, 1);
3616 sqlite3ClearTempRegCache(pParse
);
3619 #endif /* SQLITE_OMIT_SUBQUERY */
3621 #ifndef SQLITE_OMIT_SUBQUERY
3623 ** Expr pIn is an IN(...) expression. This function checks that the
3624 ** sub-select on the RHS of the IN() operator has the same number of
3625 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3626 ** a sub-query, that the LHS is a vector of size 1.
3628 int sqlite3ExprCheckIN(Parse
*pParse
, Expr
*pIn
){
3629 int nVector
= sqlite3ExprVectorSize(pIn
->pLeft
);
3630 if( ExprUseXSelect(pIn
) && !pParse
->db
->mallocFailed
){
3631 if( nVector
!=pIn
->x
.pSelect
->pEList
->nExpr
){
3632 sqlite3SubselectError(pParse
, pIn
->x
.pSelect
->pEList
->nExpr
, nVector
);
3635 }else if( nVector
!=1 ){
3636 sqlite3VectorErrorMsg(pParse
, pIn
->pLeft
);
3643 #ifndef SQLITE_OMIT_SUBQUERY
3645 ** Generate code for an IN expression.
3647 ** x IN (SELECT ...)
3648 ** x IN (value, value, ...)
3650 ** The left-hand side (LHS) is a scalar or vector expression. The
3651 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3652 ** subquery. If the RHS is a subquery, the number of result columns must
3653 ** match the number of columns in the vector on the LHS. If the RHS is
3654 ** a list of values, the LHS must be a scalar.
3656 ** The IN operator is true if the LHS value is contained within the RHS.
3657 ** The result is false if the LHS is definitely not in the RHS. The
3658 ** result is NULL if the presence of the LHS in the RHS cannot be
3659 ** determined due to NULLs.
3661 ** This routine generates code that jumps to destIfFalse if the LHS is not
3662 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3663 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3664 ** within the RHS then fall through.
3666 ** See the separate in-operator.md documentation file in the canonical
3667 ** SQLite source tree for additional information.
3669 static void sqlite3ExprCodeIN(
3670 Parse
*pParse
, /* Parsing and code generating context */
3671 Expr
*pExpr
, /* The IN expression */
3672 int destIfFalse
, /* Jump here if LHS is not contained in the RHS */
3673 int destIfNull
/* Jump here if the results are unknown due to NULLs */
3675 int rRhsHasNull
= 0; /* Register that is true if RHS contains NULL values */
3676 int eType
; /* Type of the RHS */
3677 int rLhs
; /* Register(s) holding the LHS values */
3678 int rLhsOrig
; /* LHS values prior to reordering by aiMap[] */
3679 Vdbe
*v
; /* Statement under construction */
3680 int *aiMap
= 0; /* Map from vector field to index column */
3681 char *zAff
= 0; /* Affinity string for comparisons */
3682 int nVector
; /* Size of vectors for this IN operator */
3683 int iDummy
; /* Dummy parameter to exprCodeVector() */
3684 Expr
*pLeft
; /* The LHS of the IN operator */
3685 int i
; /* loop counter */
3686 int destStep2
; /* Where to jump when NULLs seen in step 2 */
3687 int destStep6
= 0; /* Start of code for Step 6 */
3688 int addrTruthOp
; /* Address of opcode that determines the IN is true */
3689 int destNotNull
; /* Jump here if a comparison is not true in step 6 */
3690 int addrTop
; /* Top of the step-6 loop */
3691 int iTab
= 0; /* Index to use */
3692 u8 okConstFactor
= pParse
->okConstFactor
;
3694 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
3695 pLeft
= pExpr
->pLeft
;
3696 if( sqlite3ExprCheckIN(pParse
, pExpr
) ) return;
3697 zAff
= exprINAffinity(pParse
, pExpr
);
3698 nVector
= sqlite3ExprVectorSize(pExpr
->pLeft
);
3699 aiMap
= (int*)sqlite3DbMallocZero(
3700 pParse
->db
, nVector
*(sizeof(int) + sizeof(char)) + 1
3702 if( pParse
->db
->mallocFailed
) goto sqlite3ExprCodeIN_oom_error
;
3704 /* Attempt to compute the RHS. After this step, if anything other than
3705 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3706 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3707 ** the RHS has not yet been coded. */
3709 assert( v
!=0 ); /* OOM detected prior to this routine */
3710 VdbeNoopComment((v
, "begin IN expr"));
3711 eType
= sqlite3FindInIndex(pParse
, pExpr
,
3712 IN_INDEX_MEMBERSHIP
| IN_INDEX_NOOP_OK
,
3713 destIfFalse
==destIfNull
? 0 : &rRhsHasNull
,
3716 assert( pParse
->nErr
|| nVector
==1 || eType
==IN_INDEX_EPH
3717 || eType
==IN_INDEX_INDEX_ASC
|| eType
==IN_INDEX_INDEX_DESC
3720 /* Confirm that aiMap[] contains nVector integer values between 0 and
3722 for(i
=0; i
<nVector
; i
++){
3724 for(cnt
=j
=0; j
<nVector
; j
++) if( aiMap
[j
]==i
) cnt
++;
3729 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3730 ** vector, then it is stored in an array of nVector registers starting
3733 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3734 ** so that the fields are in the same order as an existing index. The
3735 ** aiMap[] array contains a mapping from the original LHS field order to
3736 ** the field order that matches the RHS index.
3738 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3739 ** even if it is constant, as OP_Affinity may be used on the register
3740 ** by code generated below. */
3741 assert( pParse
->okConstFactor
==okConstFactor
);
3742 pParse
->okConstFactor
= 0;
3743 rLhsOrig
= exprCodeVector(pParse
, pLeft
, &iDummy
);
3744 pParse
->okConstFactor
= okConstFactor
;
3745 for(i
=0; i
<nVector
&& aiMap
[i
]==i
; i
++){} /* Are LHS fields reordered? */
3747 /* LHS fields are not reordered */
3750 /* Need to reorder the LHS fields according to aiMap */
3751 rLhs
= sqlite3GetTempRange(pParse
, nVector
);
3752 for(i
=0; i
<nVector
; i
++){
3753 sqlite3VdbeAddOp3(v
, OP_Copy
, rLhsOrig
+i
, rLhs
+aiMap
[i
], 0);
3757 /* If sqlite3FindInIndex() did not find or create an index that is
3758 ** suitable for evaluating the IN operator, then evaluate using a
3759 ** sequence of comparisons.
3761 ** This is step (1) in the in-operator.md optimized algorithm.
3763 if( eType
==IN_INDEX_NOOP
){
3766 int labelOk
= sqlite3VdbeMakeLabel(pParse
);
3770 assert( ExprUseXList(pExpr
) );
3771 pList
= pExpr
->x
.pList
;
3772 pColl
= sqlite3ExprCollSeq(pParse
, pExpr
->pLeft
);
3773 if( destIfNull
!=destIfFalse
){
3774 regCkNull
= sqlite3GetTempReg(pParse
);
3775 sqlite3VdbeAddOp3(v
, OP_BitAnd
, rLhs
, rLhs
, regCkNull
);
3777 for(ii
=0; ii
<pList
->nExpr
; ii
++){
3778 r2
= sqlite3ExprCodeTemp(pParse
, pList
->a
[ii
].pExpr
, ®ToFree
);
3779 if( regCkNull
&& sqlite3ExprCanBeNull(pList
->a
[ii
].pExpr
) ){
3780 sqlite3VdbeAddOp3(v
, OP_BitAnd
, regCkNull
, r2
, regCkNull
);
3782 sqlite3ReleaseTempReg(pParse
, regToFree
);
3783 if( ii
<pList
->nExpr
-1 || destIfNull
!=destIfFalse
){
3784 int op
= rLhs
!=r2
? OP_Eq
: OP_NotNull
;
3785 sqlite3VdbeAddOp4(v
, op
, rLhs
, labelOk
, r2
,
3786 (void*)pColl
, P4_COLLSEQ
);
3787 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1 && op
==OP_Eq
);
3788 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1 && op
==OP_Eq
);
3789 VdbeCoverageIf(v
, ii
<pList
->nExpr
-1 && op
==OP_NotNull
);
3790 VdbeCoverageIf(v
, ii
==pList
->nExpr
-1 && op
==OP_NotNull
);
3791 sqlite3VdbeChangeP5(v
, zAff
[0]);
3793 int op
= rLhs
!=r2
? OP_Ne
: OP_IsNull
;
3794 assert( destIfNull
==destIfFalse
);
3795 sqlite3VdbeAddOp4(v
, op
, rLhs
, destIfFalse
, r2
,
3796 (void*)pColl
, P4_COLLSEQ
);
3797 VdbeCoverageIf(v
, op
==OP_Ne
);
3798 VdbeCoverageIf(v
, op
==OP_IsNull
);
3799 sqlite3VdbeChangeP5(v
, zAff
[0] | SQLITE_JUMPIFNULL
);
3803 sqlite3VdbeAddOp2(v
, OP_IsNull
, regCkNull
, destIfNull
); VdbeCoverage(v
);
3804 sqlite3VdbeGoto(v
, destIfFalse
);
3806 sqlite3VdbeResolveLabel(v
, labelOk
);
3807 sqlite3ReleaseTempReg(pParse
, regCkNull
);
3808 goto sqlite3ExprCodeIN_finished
;
3811 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3812 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3813 ** We will then skip the binary search of the RHS.
3815 if( destIfNull
==destIfFalse
){
3816 destStep2
= destIfFalse
;
3818 destStep2
= destStep6
= sqlite3VdbeMakeLabel(pParse
);
3820 for(i
=0; i
<nVector
; i
++){
3821 Expr
*p
= sqlite3VectorFieldSubexpr(pExpr
->pLeft
, i
);
3822 if( pParse
->nErr
) goto sqlite3ExprCodeIN_oom_error
;
3823 if( sqlite3ExprCanBeNull(p
) ){
3824 sqlite3VdbeAddOp2(v
, OP_IsNull
, rLhs
+i
, destStep2
);
3829 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3830 ** of the RHS using the LHS as a probe. If found, the result is
3833 if( eType
==IN_INDEX_ROWID
){
3834 /* In this case, the RHS is the ROWID of table b-tree and so we also
3835 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3836 ** into a single opcode. */
3837 sqlite3VdbeAddOp3(v
, OP_SeekRowid
, iTab
, destIfFalse
, rLhs
);
3839 addrTruthOp
= sqlite3VdbeAddOp0(v
, OP_Goto
); /* Return True */
3841 sqlite3VdbeAddOp4(v
, OP_Affinity
, rLhs
, nVector
, 0, zAff
, nVector
);
3842 if( destIfFalse
==destIfNull
){
3843 /* Combine Step 3 and Step 5 into a single opcode */
3844 sqlite3VdbeAddOp4Int(v
, OP_NotFound
, iTab
, destIfFalse
,
3845 rLhs
, nVector
); VdbeCoverage(v
);
3846 goto sqlite3ExprCodeIN_finished
;
3848 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3849 addrTruthOp
= sqlite3VdbeAddOp4Int(v
, OP_Found
, iTab
, 0,
3850 rLhs
, nVector
); VdbeCoverage(v
);
3853 /* Step 4. If the RHS is known to be non-NULL and we did not find
3854 ** an match on the search above, then the result must be FALSE.
3856 if( rRhsHasNull
&& nVector
==1 ){
3857 sqlite3VdbeAddOp2(v
, OP_NotNull
, rRhsHasNull
, destIfFalse
);
3861 /* Step 5. If we do not care about the difference between NULL and
3862 ** FALSE, then just return false.
3864 if( destIfFalse
==destIfNull
) sqlite3VdbeGoto(v
, destIfFalse
);
3866 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3867 ** If any comparison is NULL, then the result is NULL. If all
3868 ** comparisons are FALSE then the final result is FALSE.
3870 ** For a scalar LHS, it is sufficient to check just the first row
3873 if( destStep6
) sqlite3VdbeResolveLabel(v
, destStep6
);
3874 addrTop
= sqlite3VdbeAddOp2(v
, OP_Rewind
, iTab
, destIfFalse
);
3877 destNotNull
= sqlite3VdbeMakeLabel(pParse
);
3879 /* For nVector==1, combine steps 6 and 7 by immediately returning
3880 ** FALSE if the first comparison is not NULL */
3881 destNotNull
= destIfFalse
;
3883 for(i
=0; i
<nVector
; i
++){
3886 int r3
= sqlite3GetTempReg(pParse
);
3887 p
= sqlite3VectorFieldSubexpr(pLeft
, i
);
3888 pColl
= sqlite3ExprCollSeq(pParse
, p
);
3889 sqlite3VdbeAddOp3(v
, OP_Column
, iTab
, i
, r3
);
3890 sqlite3VdbeAddOp4(v
, OP_Ne
, rLhs
+i
, destNotNull
, r3
,
3891 (void*)pColl
, P4_COLLSEQ
);
3893 sqlite3ReleaseTempReg(pParse
, r3
);
3895 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfNull
);
3897 sqlite3VdbeResolveLabel(v
, destNotNull
);
3898 sqlite3VdbeAddOp2(v
, OP_Next
, iTab
, addrTop
+1);
3901 /* Step 7: If we reach this point, we know that the result must
3903 sqlite3VdbeAddOp2(v
, OP_Goto
, 0, destIfFalse
);
3906 /* Jumps here in order to return true. */
3907 sqlite3VdbeJumpHere(v
, addrTruthOp
);
3909 sqlite3ExprCodeIN_finished
:
3910 if( rLhs
!=rLhsOrig
) sqlite3ReleaseTempReg(pParse
, rLhs
);
3911 VdbeComment((v
, "end IN expr"));
3912 sqlite3ExprCodeIN_oom_error
:
3913 sqlite3DbFree(pParse
->db
, aiMap
);
3914 sqlite3DbFree(pParse
->db
, zAff
);
3916 #endif /* SQLITE_OMIT_SUBQUERY */
3918 #ifndef SQLITE_OMIT_FLOATING_POINT
3920 ** Generate an instruction that will put the floating point
3921 ** value described by z[0..n-1] into register iMem.
3923 ** The z[] string will probably not be zero-terminated. But the
3924 ** z[n] character is guaranteed to be something that does not look
3925 ** like the continuation of the number.
3927 static void codeReal(Vdbe
*v
, const char *z
, int negateFlag
, int iMem
){
3930 sqlite3AtoF(z
, &value
, sqlite3Strlen30(z
), SQLITE_UTF8
);
3931 assert( !sqlite3IsNaN(value
) ); /* The new AtoF never returns NaN */
3932 if( negateFlag
) value
= -value
;
3933 sqlite3VdbeAddOp4Dup8(v
, OP_Real
, 0, iMem
, 0, (u8
*)&value
, P4_REAL
);
3940 ** Generate an instruction that will put the integer describe by
3941 ** text z[0..n-1] into register iMem.
3943 ** Expr.u.zToken is always UTF8 and zero-terminated.
3945 static void codeInteger(Parse
*pParse
, Expr
*pExpr
, int negFlag
, int iMem
){
3946 Vdbe
*v
= pParse
->pVdbe
;
3947 if( pExpr
->flags
& EP_IntValue
){
3948 int i
= pExpr
->u
.iValue
;
3950 if( negFlag
) i
= -i
;
3951 sqlite3VdbeAddOp2(v
, OP_Integer
, i
, iMem
);
3955 const char *z
= pExpr
->u
.zToken
;
3957 c
= sqlite3DecOrHexToI64(z
, &value
);
3958 if( (c
==3 && !negFlag
) || (c
==2) || (negFlag
&& value
==SMALLEST_INT64
)){
3959 #ifdef SQLITE_OMIT_FLOATING_POINT
3960 sqlite3ErrorMsg(pParse
, "oversized integer: %s%#T", negFlag
?"-":"",pExpr
);
3962 #ifndef SQLITE_OMIT_HEX_INTEGER
3963 if( sqlite3_strnicmp(z
,"0x",2)==0 ){
3964 sqlite3ErrorMsg(pParse
, "hex literal too big: %s%#T",
3965 negFlag
?"-":"",pExpr
);
3969 codeReal(v
, z
, negFlag
, iMem
);
3973 if( negFlag
){ value
= c
==3 ? SMALLEST_INT64
: -value
; }
3974 sqlite3VdbeAddOp4Dup8(v
, OP_Int64
, 0, iMem
, 0, (u8
*)&value
, P4_INT64
);
3980 /* Generate code that will load into register regOut a value that is
3981 ** appropriate for the iIdxCol-th column of index pIdx.
3983 void sqlite3ExprCodeLoadIndexColumn(
3984 Parse
*pParse
, /* The parsing context */
3985 Index
*pIdx
, /* The index whose column is to be loaded */
3986 int iTabCur
, /* Cursor pointing to a table row */
3987 int iIdxCol
, /* The column of the index to be loaded */
3988 int regOut
/* Store the index column value in this register */
3990 i16 iTabCol
= pIdx
->aiColumn
[iIdxCol
];
3991 if( iTabCol
==XN_EXPR
){
3992 assert( pIdx
->aColExpr
);
3993 assert( pIdx
->aColExpr
->nExpr
>iIdxCol
);
3994 pParse
->iSelfTab
= iTabCur
+ 1;
3995 sqlite3ExprCodeCopy(pParse
, pIdx
->aColExpr
->a
[iIdxCol
].pExpr
, regOut
);
3996 pParse
->iSelfTab
= 0;
3998 sqlite3ExprCodeGetColumnOfTable(pParse
->pVdbe
, pIdx
->pTable
, iTabCur
,
4003 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4005 ** Generate code that will compute the value of generated column pCol
4006 ** and store the result in register regOut
4008 void sqlite3ExprCodeGeneratedColumn(
4009 Parse
*pParse
, /* Parsing context */
4010 Table
*pTab
, /* Table containing the generated column */
4011 Column
*pCol
, /* The generated column */
4012 int regOut
/* Put the result in this register */
4015 Vdbe
*v
= pParse
->pVdbe
;
4016 int nErr
= pParse
->nErr
;
4018 assert( pParse
->iSelfTab
!=0 );
4019 if( pParse
->iSelfTab
>0 ){
4020 iAddr
= sqlite3VdbeAddOp3(v
, OP_IfNullRow
, pParse
->iSelfTab
-1, 0, regOut
);
4024 sqlite3ExprCodeCopy(pParse
, sqlite3ColumnExpr(pTab
,pCol
), regOut
);
4025 if( pCol
->affinity
>=SQLITE_AFF_TEXT
){
4026 sqlite3VdbeAddOp4(v
, OP_Affinity
, regOut
, 1, 0, &pCol
->affinity
, 1);
4028 if( iAddr
) sqlite3VdbeJumpHere(v
, iAddr
);
4029 if( pParse
->nErr
>nErr
) pParse
->db
->errByteOffset
= -1;
4031 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4034 ** Generate code to extract the value of the iCol-th column of a table.
4036 void sqlite3ExprCodeGetColumnOfTable(
4037 Vdbe
*v
, /* Parsing context */
4038 Table
*pTab
, /* The table containing the value */
4039 int iTabCur
, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
4040 int iCol
, /* Index of the column to extract */
4041 int regOut
/* Extract the value into this register */
4046 assert( iCol
!=XN_EXPR
);
4047 if( iCol
<0 || iCol
==pTab
->iPKey
){
4048 sqlite3VdbeAddOp2(v
, OP_Rowid
, iTabCur
, regOut
);
4049 VdbeComment((v
, "%s.rowid", pTab
->zName
));
4053 if( IsVirtual(pTab
) ){
4056 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4057 }else if( (pCol
= &pTab
->aCol
[iCol
])->colFlags
& COLFLAG_VIRTUAL
){
4058 Parse
*pParse
= sqlite3VdbeParser(v
);
4059 if( pCol
->colFlags
& COLFLAG_BUSY
){
4060 sqlite3ErrorMsg(pParse
, "generated column loop on \"%s\"",
4063 int savedSelfTab
= pParse
->iSelfTab
;
4064 pCol
->colFlags
|= COLFLAG_BUSY
;
4065 pParse
->iSelfTab
= iTabCur
+1;
4066 sqlite3ExprCodeGeneratedColumn(pParse
, pTab
, pCol
, regOut
);
4067 pParse
->iSelfTab
= savedSelfTab
;
4068 pCol
->colFlags
&= ~COLFLAG_BUSY
;
4072 }else if( !HasRowid(pTab
) ){
4073 testcase( iCol
!=sqlite3TableColumnToStorage(pTab
, iCol
) );
4074 x
= sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab
), iCol
);
4077 x
= sqlite3TableColumnToStorage(pTab
,iCol
);
4078 testcase( x
!=iCol
);
4081 sqlite3VdbeAddOp3(v
, op
, iTabCur
, x
, regOut
);
4082 sqlite3ColumnDefault(v
, pTab
, iCol
, regOut
);
4087 ** Generate code that will extract the iColumn-th column from
4088 ** table pTab and store the column value in register iReg.
4090 ** There must be an open cursor to pTab in iTable when this routine
4091 ** is called. If iColumn<0 then code is generated that extracts the rowid.
4093 int sqlite3ExprCodeGetColumn(
4094 Parse
*pParse
, /* Parsing and code generating context */
4095 Table
*pTab
, /* Description of the table we are reading from */
4096 int iColumn
, /* Index of the table column */
4097 int iTable
, /* The cursor pointing to the table */
4098 int iReg
, /* Store results here */
4099 u8 p5
/* P5 value for OP_Column + FLAGS */
4101 assert( pParse
->pVdbe
!=0 );
4102 assert( (p5
& (OPFLAG_NOCHNG
|OPFLAG_TYPEOFARG
|OPFLAG_LENGTHARG
))==p5
);
4103 assert( IsVirtual(pTab
) || (p5
& OPFLAG_NOCHNG
)==0 );
4104 sqlite3ExprCodeGetColumnOfTable(pParse
->pVdbe
, pTab
, iTable
, iColumn
, iReg
);
4106 VdbeOp
*pOp
= sqlite3VdbeGetLastOp(pParse
->pVdbe
);
4107 if( pOp
->opcode
==OP_Column
) pOp
->p5
= p5
;
4108 if( pOp
->opcode
==OP_VColumn
) pOp
->p5
= (p5
& OPFLAG_NOCHNG
);
4114 ** Generate code to move content from registers iFrom...iFrom+nReg-1
4115 ** over to iTo..iTo+nReg-1.
4117 void sqlite3ExprCodeMove(Parse
*pParse
, int iFrom
, int iTo
, int nReg
){
4118 sqlite3VdbeAddOp3(pParse
->pVdbe
, OP_Move
, iFrom
, iTo
, nReg
);
4122 ** Convert a scalar expression node to a TK_REGISTER referencing
4123 ** register iReg. The caller must ensure that iReg already contains
4124 ** the correct value for the expression.
4126 static void exprToRegister(Expr
*pExpr
, int iReg
){
4127 Expr
*p
= sqlite3ExprSkipCollateAndLikely(pExpr
);
4128 if( NEVER(p
==0) ) return;
4130 p
->op
= TK_REGISTER
;
4132 ExprClearProperty(p
, EP_Skip
);
4136 ** Evaluate an expression (either a vector or a scalar expression) and store
4137 ** the result in contiguous temporary registers. Return the index of
4138 ** the first register used to store the result.
4140 ** If the returned result register is a temporary scalar, then also write
4141 ** that register number into *piFreeable. If the returned result register
4142 ** is not a temporary or if the expression is a vector set *piFreeable
4145 static int exprCodeVector(Parse
*pParse
, Expr
*p
, int *piFreeable
){
4147 int nResult
= sqlite3ExprVectorSize(p
);
4149 iResult
= sqlite3ExprCodeTemp(pParse
, p
, piFreeable
);
4152 if( p
->op
==TK_SELECT
){
4153 #if SQLITE_OMIT_SUBQUERY
4156 iResult
= sqlite3CodeSubselect(pParse
, p
);
4160 iResult
= pParse
->nMem
+1;
4161 pParse
->nMem
+= nResult
;
4162 assert( ExprUseXList(p
) );
4163 for(i
=0; i
<nResult
; i
++){
4164 sqlite3ExprCodeFactorable(pParse
, p
->x
.pList
->a
[i
].pExpr
, i
+iResult
);
4172 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
4173 ** so that a subsequent copy will not be merged into this one.
4175 static void setDoNotMergeFlagOnCopy(Vdbe
*v
){
4176 if( sqlite3VdbeGetLastOp(v
)->opcode
==OP_Copy
){
4177 sqlite3VdbeChangeP5(v
, 1); /* Tag trailing OP_Copy as not mergeable */
4182 ** Generate code to implement special SQL functions that are implemented
4183 ** in-line rather than by using the usual callbacks.
4185 static int exprCodeInlineFunction(
4186 Parse
*pParse
, /* Parsing context */
4187 ExprList
*pFarg
, /* List of function arguments */
4188 int iFuncId
, /* Function ID. One of the INTFUNC_... values */
4189 int target
/* Store function result in this register */
4192 Vdbe
*v
= pParse
->pVdbe
;
4195 nFarg
= pFarg
->nExpr
;
4196 assert( nFarg
>0 ); /* All in-line functions have at least one argument */
4198 case INLINEFUNC_coalesce
: {
4199 /* Attempt a direct implementation of the built-in COALESCE() and
4200 ** IFNULL() functions. This avoids unnecessary evaluation of
4201 ** arguments past the first non-NULL argument.
4203 int endCoalesce
= sqlite3VdbeMakeLabel(pParse
);
4206 sqlite3ExprCode(pParse
, pFarg
->a
[0].pExpr
, target
);
4207 for(i
=1; i
<nFarg
; i
++){
4208 sqlite3VdbeAddOp2(v
, OP_NotNull
, target
, endCoalesce
);
4210 sqlite3ExprCode(pParse
, pFarg
->a
[i
].pExpr
, target
);
4212 setDoNotMergeFlagOnCopy(v
);
4213 sqlite3VdbeResolveLabel(v
, endCoalesce
);
4216 case INLINEFUNC_iif
: {
4218 memset(&caseExpr
, 0, sizeof(caseExpr
));
4219 caseExpr
.op
= TK_CASE
;
4220 caseExpr
.x
.pList
= pFarg
;
4221 return sqlite3ExprCodeTarget(pParse
, &caseExpr
, target
);
4223 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4224 case INLINEFUNC_sqlite_offset
: {
4225 Expr
*pArg
= pFarg
->a
[0].pExpr
;
4226 if( pArg
->op
==TK_COLUMN
&& pArg
->iTable
>=0 ){
4227 sqlite3VdbeAddOp3(v
, OP_Offset
, pArg
->iTable
, pArg
->iColumn
, target
);
4229 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4235 /* The UNLIKELY() function is a no-op. The result is the value
4236 ** of the first argument.
4238 assert( nFarg
==1 || nFarg
==2 );
4239 target
= sqlite3ExprCodeTarget(pParse
, pFarg
->a
[0].pExpr
, target
);
4243 /***********************************************************************
4244 ** Test-only SQL functions that are only usable if enabled
4245 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4247 #if !defined(SQLITE_UNTESTABLE)
4248 case INLINEFUNC_expr_compare
: {
4249 /* Compare two expressions using sqlite3ExprCompare() */
4251 sqlite3VdbeAddOp2(v
, OP_Integer
,
4252 sqlite3ExprCompare(0,pFarg
->a
[0].pExpr
, pFarg
->a
[1].pExpr
,-1),
4257 case INLINEFUNC_expr_implies_expr
: {
4258 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4260 sqlite3VdbeAddOp2(v
, OP_Integer
,
4261 sqlite3ExprImpliesExpr(pParse
,pFarg
->a
[0].pExpr
, pFarg
->a
[1].pExpr
,-1),
4266 case INLINEFUNC_implies_nonnull_row
: {
4267 /* Result of sqlite3ExprImpliesNonNullRow() */
4270 pA1
= pFarg
->a
[1].pExpr
;
4271 if( pA1
->op
==TK_COLUMN
){
4272 sqlite3VdbeAddOp2(v
, OP_Integer
,
4273 sqlite3ExprImpliesNonNullRow(pFarg
->a
[0].pExpr
,pA1
->iTable
,1),
4276 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4281 case INLINEFUNC_affinity
: {
4282 /* The AFFINITY() function evaluates to a string that describes
4283 ** the type affinity of the argument. This is used for testing of
4284 ** the SQLite type logic.
4286 const char *azAff
[] = { "blob", "text", "numeric", "integer",
4287 "real", "flexnum" };
4290 aff
= sqlite3ExprAffinity(pFarg
->a
[0].pExpr
);
4291 assert( aff
<=SQLITE_AFF_NONE
4292 || (aff
>=SQLITE_AFF_BLOB
&& aff
<=SQLITE_AFF_FLEXNUM
) );
4293 sqlite3VdbeLoadString(v
, target
,
4294 (aff
<=SQLITE_AFF_NONE
) ? "none" : azAff
[aff
-SQLITE_AFF_BLOB
]);
4297 #endif /* !defined(SQLITE_UNTESTABLE) */
4303 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4304 ** If it is, then resolve the expression by reading from the index and
4305 ** return the register into which the value has been read. If pExpr is
4306 ** not an indexed expression, then return negative.
4308 static SQLITE_NOINLINE
int sqlite3IndexedExprLookup(
4309 Parse
*pParse
, /* The parsing context */
4310 Expr
*pExpr
, /* The expression to potentially bypass */
4311 int target
/* Where to store the result of the expression */
4315 for(p
=pParse
->pIdxEpr
; p
; p
=p
->pIENext
){
4317 int iDataCur
= p
->iDataCur
;
4318 if( iDataCur
<0 ) continue;
4319 if( pParse
->iSelfTab
){
4320 if( p
->iDataCur
!=pParse
->iSelfTab
-1 ) continue;
4323 if( sqlite3ExprCompare(0, pExpr
, p
->pExpr
, iDataCur
)!=0 ) continue;
4324 assert( p
->aff
>=SQLITE_AFF_BLOB
&& p
->aff
<=SQLITE_AFF_NUMERIC
);
4325 exprAff
= sqlite3ExprAffinity(pExpr
);
4326 if( (exprAff
<=SQLITE_AFF_BLOB
&& p
->aff
!=SQLITE_AFF_BLOB
)
4327 || (exprAff
==SQLITE_AFF_TEXT
&& p
->aff
!=SQLITE_AFF_TEXT
)
4328 || (exprAff
>=SQLITE_AFF_NUMERIC
&& p
->aff
!=SQLITE_AFF_NUMERIC
)
4330 /* Affinity mismatch on a generated column */
4336 if( p
->bMaybeNullRow
){
4337 /* If the index is on a NULL row due to an outer join, then we
4338 ** cannot extract the value from the index. The value must be
4339 ** computed using the original expression. */
4340 int addr
= sqlite3VdbeCurrentAddr(v
);
4341 sqlite3VdbeAddOp3(v
, OP_IfNullRow
, p
->iIdxCur
, addr
+3, target
);
4343 sqlite3VdbeAddOp3(v
, OP_Column
, p
->iIdxCur
, p
->iIdxCol
, target
);
4344 VdbeComment((v
, "%s expr-column %d", p
->zIdxName
, p
->iIdxCol
));
4345 sqlite3VdbeGoto(v
, 0);
4346 p
= pParse
->pIdxEpr
;
4347 pParse
->pIdxEpr
= 0;
4348 sqlite3ExprCode(pParse
, pExpr
, target
);
4349 pParse
->pIdxEpr
= p
;
4350 sqlite3VdbeJumpHere(v
, addr
+2);
4352 sqlite3VdbeAddOp3(v
, OP_Column
, p
->iIdxCur
, p
->iIdxCol
, target
);
4353 VdbeComment((v
, "%s expr-column %d", p
->zIdxName
, p
->iIdxCol
));
4357 return -1; /* Not found */
4362 ** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This
4363 ** function checks the Parse.pIdxPartExpr list to see if this column
4364 ** can be replaced with a constant value. If so, it generates code to
4365 ** put the constant value in a register (ideally, but not necessarily,
4366 ** register iTarget) and returns the register number.
4368 ** Or, if the TK_COLUMN cannot be replaced by a constant, zero is
4371 static int exprPartidxExprLookup(Parse
*pParse
, Expr
*pExpr
, int iTarget
){
4373 for(p
=pParse
->pIdxPartExpr
; p
; p
=p
->pIENext
){
4374 if( pExpr
->iColumn
==p
->iIdxCol
&& pExpr
->iTable
==p
->iDataCur
){
4375 Vdbe
*v
= pParse
->pVdbe
;
4379 if( p
->bMaybeNullRow
){
4380 addr
= sqlite3VdbeAddOp1(v
, OP_IfNullRow
, p
->iIdxCur
);
4382 ret
= sqlite3ExprCodeTarget(pParse
, p
->pExpr
, iTarget
);
4383 sqlite3VdbeAddOp4(pParse
->pVdbe
, OP_Affinity
, ret
, 1, 0,
4384 (const char*)&p
->aff
, 1);
4386 sqlite3VdbeJumpHere(v
, addr
);
4387 sqlite3VdbeChangeP3(v
, addr
, ret
);
4397 ** Generate code into the current Vdbe to evaluate the given
4398 ** expression. Attempt to store the results in register "target".
4399 ** Return the register where results are stored.
4401 ** With this routine, there is no guarantee that results will
4402 ** be stored in target. The result might be stored in some other
4403 ** register if it is convenient to do so. The calling function
4404 ** must check the return code and move the results to the desired
4407 int sqlite3ExprCodeTarget(Parse
*pParse
, Expr
*pExpr
, int target
){
4408 Vdbe
*v
= pParse
->pVdbe
; /* The VM under construction */
4409 int op
; /* The opcode being coded */
4410 int inReg
= target
; /* Results stored in register inReg */
4411 int regFree1
= 0; /* If non-zero free this temporary register */
4412 int regFree2
= 0; /* If non-zero free this temporary register */
4413 int r1
, r2
; /* Various register numbers */
4414 Expr tempX
; /* Temporary expression node */
4417 assert( target
>0 && target
<=pParse
->nMem
);
4423 }else if( pParse
->pIdxEpr
!=0
4424 && !ExprHasProperty(pExpr
, EP_Leaf
)
4425 && (r1
= sqlite3IndexedExprLookup(pParse
, pExpr
, target
))>=0
4429 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
4432 assert( op
!=TK_ORDER
);
4434 case TK_AGG_COLUMN
: {
4435 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
4436 struct AggInfo_col
*pCol
;
4437 assert( pAggInfo
!=0 );
4438 assert( pExpr
->iAgg
>=0 );
4439 if( pExpr
->iAgg
>=pAggInfo
->nColumn
){
4440 /* Happens when the left table of a RIGHT JOIN is null and
4441 ** is using an expression index */
4442 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4443 #ifdef SQLITE_VDBE_COVERAGE
4444 /* Verify that the OP_Null above is exercised by tests
4445 ** tag-20230325-2 */
4446 sqlite3VdbeAddOp3(v
, OP_NotNull
, target
, 1, 20230325);
4447 VdbeCoverageNeverTaken(v
);
4451 pCol
= &pAggInfo
->aCol
[pExpr
->iAgg
];
4452 if( !pAggInfo
->directMode
){
4453 return AggInfoColumnReg(pAggInfo
, pExpr
->iAgg
);
4454 }else if( pAggInfo
->useSortingIdx
){
4455 Table
*pTab
= pCol
->pTab
;
4456 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
4457 pCol
->iSorterColumn
, target
);
4459 /* No comment added */
4460 }else if( pCol
->iColumn
<0 ){
4461 VdbeComment((v
,"%s.rowid",pTab
->zName
));
4463 VdbeComment((v
,"%s.%s",
4464 pTab
->zName
, pTab
->aCol
[pCol
->iColumn
].zCnName
));
4465 if( pTab
->aCol
[pCol
->iColumn
].affinity
==SQLITE_AFF_REAL
){
4466 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4470 }else if( pExpr
->y
.pTab
==0 ){
4471 /* This case happens when the argument to an aggregate function
4472 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4473 sqlite3VdbeAddOp3(v
, OP_Column
, pExpr
->iTable
, pExpr
->iColumn
, target
);
4476 /* Otherwise, fall thru into the TK_COLUMN case */
4477 /* no break */ deliberate_fall_through
4480 int iTab
= pExpr
->iTable
;
4482 if( ExprHasProperty(pExpr
, EP_FixedCol
) ){
4483 /* This COLUMN expression is really a constant due to WHERE clause
4484 ** constraints, and that constant is coded by the pExpr->pLeft
4485 ** expression. However, make sure the constant has the correct
4486 ** datatype by applying the Affinity of the table column to the
4490 iReg
= sqlite3ExprCodeTarget(pParse
, pExpr
->pLeft
,target
);
4491 assert( ExprUseYTab(pExpr
) );
4492 assert( pExpr
->y
.pTab
!=0 );
4493 aff
= sqlite3TableColumnAffinity(pExpr
->y
.pTab
, pExpr
->iColumn
);
4494 if( aff
>SQLITE_AFF_BLOB
){
4495 static const char zAff
[] = "B\000C\000D\000E\000F";
4496 assert( SQLITE_AFF_BLOB
=='A' );
4497 assert( SQLITE_AFF_TEXT
=='B' );
4498 sqlite3VdbeAddOp4(v
, OP_Affinity
, iReg
, 1, 0,
4499 &zAff
[(aff
-'B')*2], P4_STATIC
);
4504 if( pParse
->iSelfTab
<0 ){
4505 /* Other columns in the same row for CHECK constraints or
4506 ** generated columns or for inserting into partial index.
4507 ** The row is unpacked into registers beginning at
4508 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4509 ** immediately prior to the first column.
4514 int iCol
= pExpr
->iColumn
;
4515 assert( ExprUseYTab(pExpr
) );
4516 pTab
= pExpr
->y
.pTab
;
4518 assert( iCol
>=XN_ROWID
);
4519 assert( iCol
<pTab
->nCol
);
4521 return -1-pParse
->iSelfTab
;
4523 pCol
= pTab
->aCol
+ iCol
;
4524 testcase( iCol
!=sqlite3TableColumnToStorage(pTab
,iCol
) );
4525 iSrc
= sqlite3TableColumnToStorage(pTab
, iCol
) - pParse
->iSelfTab
;
4526 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4527 if( pCol
->colFlags
& COLFLAG_GENERATED
){
4528 if( pCol
->colFlags
& COLFLAG_BUSY
){
4529 sqlite3ErrorMsg(pParse
, "generated column loop on \"%s\"",
4533 pCol
->colFlags
|= COLFLAG_BUSY
;
4534 if( pCol
->colFlags
& COLFLAG_NOTAVAIL
){
4535 sqlite3ExprCodeGeneratedColumn(pParse
, pTab
, pCol
, iSrc
);
4537 pCol
->colFlags
&= ~(COLFLAG_BUSY
|COLFLAG_NOTAVAIL
);
4540 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4541 if( pCol
->affinity
==SQLITE_AFF_REAL
){
4542 sqlite3VdbeAddOp2(v
, OP_SCopy
, iSrc
, target
);
4543 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
4549 /* Coding an expression that is part of an index where column names
4550 ** in the index refer to the table to which the index belongs */
4551 iTab
= pParse
->iSelfTab
- 1;
4554 else if( pParse
->pIdxPartExpr
4555 && 0!=(r1
= exprPartidxExprLookup(pParse
, pExpr
, target
))
4559 assert( ExprUseYTab(pExpr
) );
4560 assert( pExpr
->y
.pTab
!=0 );
4561 iReg
= sqlite3ExprCodeGetColumn(pParse
, pExpr
->y
.pTab
,
4562 pExpr
->iColumn
, iTab
, target
,
4567 codeInteger(pParse
, pExpr
, 0, target
);
4570 case TK_TRUEFALSE
: {
4571 sqlite3VdbeAddOp2(v
, OP_Integer
, sqlite3ExprTruthValue(pExpr
), target
);
4574 #ifndef SQLITE_OMIT_FLOATING_POINT
4576 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4577 codeReal(v
, pExpr
->u
.zToken
, 0, target
);
4582 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4583 sqlite3VdbeLoadString(v
, target
, pExpr
->u
.zToken
);
4587 /* Make NULL the default case so that if a bug causes an illegal
4588 ** Expr node to be passed into this function, it will be handled
4589 ** sanely and not crash. But keep the assert() to bring the problem
4590 ** to the attention of the developers. */
4591 assert( op
==TK_NULL
|| op
==TK_ERROR
|| pParse
->db
->mallocFailed
);
4592 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4595 #ifndef SQLITE_OMIT_BLOB_LITERAL
4600 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4601 assert( pExpr
->u
.zToken
[0]=='x' || pExpr
->u
.zToken
[0]=='X' );
4602 assert( pExpr
->u
.zToken
[1]=='\'' );
4603 z
= &pExpr
->u
.zToken
[2];
4604 n
= sqlite3Strlen30(z
) - 1;
4605 assert( z
[n
]=='\'' );
4606 zBlob
= sqlite3HexToBlob(sqlite3VdbeDb(v
), z
, n
);
4607 sqlite3VdbeAddOp4(v
, OP_Blob
, n
/2, target
, 0, zBlob
, P4_DYNAMIC
);
4612 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4613 assert( pExpr
->u
.zToken
!=0 );
4614 assert( pExpr
->u
.zToken
[0]!=0 );
4615 sqlite3VdbeAddOp2(v
, OP_Variable
, pExpr
->iColumn
, target
);
4616 if( pExpr
->u
.zToken
[1]!=0 ){
4617 const char *z
= sqlite3VListNumToName(pParse
->pVList
, pExpr
->iColumn
);
4618 assert( pExpr
->u
.zToken
[0]=='?' || (z
&& !strcmp(pExpr
->u
.zToken
, z
)) );
4619 pParse
->pVList
[0] = 0; /* Indicate VList may no longer be enlarged */
4620 sqlite3VdbeAppendP4(v
, (char*)z
, P4_STATIC
);
4625 return pExpr
->iTable
;
4627 #ifndef SQLITE_OMIT_CAST
4629 /* Expressions of the form: CAST(pLeft AS token) */
4630 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
4631 assert( inReg
==target
);
4632 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4633 sqlite3VdbeAddOp2(v
, OP_Cast
, target
,
4634 sqlite3AffinityType(pExpr
->u
.zToken
, 0));
4637 #endif /* SQLITE_OMIT_CAST */
4640 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
4649 Expr
*pLeft
= pExpr
->pLeft
;
4650 if( sqlite3ExprIsVector(pLeft
) ){
4651 codeVectorCompare(pParse
, pExpr
, target
, op
, p5
);
4653 r1
= sqlite3ExprCodeTemp(pParse
, pLeft
, ®Free1
);
4654 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
4655 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, inReg
);
4656 codeCompare(pParse
, pLeft
, pExpr
->pRight
, op
, r1
, r2
,
4657 sqlite3VdbeCurrentAddr(v
)+2, p5
,
4658 ExprHasProperty(pExpr
,EP_Commuted
));
4659 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
4660 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
4661 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
4662 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
4663 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
); VdbeCoverageIf(v
,op
==OP_Eq
);
4664 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
); VdbeCoverageIf(v
,op
==OP_Ne
);
4665 if( p5
==SQLITE_NULLEQ
){
4666 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, inReg
);
4668 sqlite3VdbeAddOp3(v
, OP_ZeroOrNull
, r1
, inReg
, r2
);
4670 testcase( regFree1
==0 );
4671 testcase( regFree2
==0 );
4687 assert( TK_AND
==OP_And
); testcase( op
==TK_AND
);
4688 assert( TK_OR
==OP_Or
); testcase( op
==TK_OR
);
4689 assert( TK_PLUS
==OP_Add
); testcase( op
==TK_PLUS
);
4690 assert( TK_MINUS
==OP_Subtract
); testcase( op
==TK_MINUS
);
4691 assert( TK_REM
==OP_Remainder
); testcase( op
==TK_REM
);
4692 assert( TK_BITAND
==OP_BitAnd
); testcase( op
==TK_BITAND
);
4693 assert( TK_BITOR
==OP_BitOr
); testcase( op
==TK_BITOR
);
4694 assert( TK_SLASH
==OP_Divide
); testcase( op
==TK_SLASH
);
4695 assert( TK_LSHIFT
==OP_ShiftLeft
); testcase( op
==TK_LSHIFT
);
4696 assert( TK_RSHIFT
==OP_ShiftRight
); testcase( op
==TK_RSHIFT
);
4697 assert( TK_CONCAT
==OP_Concat
); testcase( op
==TK_CONCAT
);
4698 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4699 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
4700 sqlite3VdbeAddOp3(v
, op
, r2
, r1
, target
);
4701 testcase( regFree1
==0 );
4702 testcase( regFree2
==0 );
4706 Expr
*pLeft
= pExpr
->pLeft
;
4708 if( pLeft
->op
==TK_INTEGER
){
4709 codeInteger(pParse
, pLeft
, 1, target
);
4711 #ifndef SQLITE_OMIT_FLOATING_POINT
4712 }else if( pLeft
->op
==TK_FLOAT
){
4713 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4714 codeReal(v
, pLeft
->u
.zToken
, 1, target
);
4718 tempX
.op
= TK_INTEGER
;
4719 tempX
.flags
= EP_IntValue
|EP_TokenOnly
;
4721 ExprClearVVAProperties(&tempX
);
4722 r1
= sqlite3ExprCodeTemp(pParse
, &tempX
, ®Free1
);
4723 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free2
);
4724 sqlite3VdbeAddOp3(v
, OP_Subtract
, r2
, r1
, target
);
4725 testcase( regFree2
==0 );
4731 assert( TK_BITNOT
==OP_BitNot
); testcase( op
==TK_BITNOT
);
4732 assert( TK_NOT
==OP_Not
); testcase( op
==TK_NOT
);
4733 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4734 testcase( regFree1
==0 );
4735 sqlite3VdbeAddOp2(v
, op
, r1
, inReg
);
4739 int isTrue
; /* IS TRUE or IS NOT TRUE */
4740 int bNormal
; /* IS TRUE or IS FALSE */
4741 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4742 testcase( regFree1
==0 );
4743 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
4744 bNormal
= pExpr
->op2
==TK_IS
;
4745 testcase( isTrue
&& bNormal
);
4746 testcase( !isTrue
&& bNormal
);
4747 sqlite3VdbeAddOp4Int(v
, OP_IsTrue
, r1
, inReg
, !isTrue
, isTrue
^ bNormal
);
4753 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
4754 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
4755 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
4756 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
4757 testcase( regFree1
==0 );
4758 addr
= sqlite3VdbeAddOp1(v
, op
, r1
);
4759 VdbeCoverageIf(v
, op
==TK_ISNULL
);
4760 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
4761 sqlite3VdbeAddOp2(v
, OP_Integer
, 0, target
);
4762 sqlite3VdbeJumpHere(v
, addr
);
4765 case TK_AGG_FUNCTION
: {
4766 AggInfo
*pInfo
= pExpr
->pAggInfo
;
4768 || NEVER(pExpr
->iAgg
<0)
4769 || NEVER(pExpr
->iAgg
>=pInfo
->nFunc
)
4771 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4772 sqlite3ErrorMsg(pParse
, "misuse of aggregate: %#T()", pExpr
);
4774 return AggInfoFuncReg(pInfo
, pExpr
->iAgg
);
4779 ExprList
*pFarg
; /* List of function arguments */
4780 int nFarg
; /* Number of function arguments */
4781 FuncDef
*pDef
; /* The function definition object */
4782 const char *zId
; /* The function name */
4783 u32 constMask
= 0; /* Mask of function arguments that are constant */
4784 int i
; /* Loop counter */
4785 sqlite3
*db
= pParse
->db
; /* The database connection */
4786 u8 enc
= ENC(db
); /* The text encoding used by this database */
4787 CollSeq
*pColl
= 0; /* A collating sequence */
4789 #ifndef SQLITE_OMIT_WINDOWFUNC
4790 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
4791 return pExpr
->y
.pWin
->regResult
;
4795 if( ConstFactorOk(pParse
) && sqlite3ExprIsConstantNotJoin(pExpr
) ){
4796 /* SQL functions can be expensive. So try to avoid running them
4797 ** multiple times if we know they always give the same result */
4798 return sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, -1);
4800 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
) );
4801 assert( ExprUseXList(pExpr
) );
4802 pFarg
= pExpr
->x
.pList
;
4803 nFarg
= pFarg
? pFarg
->nExpr
: 0;
4804 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
4805 zId
= pExpr
->u
.zToken
;
4806 pDef
= sqlite3FindFunction(db
, zId
, nFarg
, enc
, 0);
4807 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4808 if( pDef
==0 && pParse
->explain
){
4809 pDef
= sqlite3FindFunction(db
, "unknown", nFarg
, enc
, 0);
4812 if( pDef
==0 || pDef
->xFinalize
!=0 ){
4813 sqlite3ErrorMsg(pParse
, "unknown function: %#T()", pExpr
);
4816 if( (pDef
->funcFlags
& SQLITE_FUNC_INLINE
)!=0 && ALWAYS(pFarg
!=0) ){
4817 assert( (pDef
->funcFlags
& SQLITE_FUNC_UNSAFE
)==0 );
4818 assert( (pDef
->funcFlags
& SQLITE_FUNC_DIRECT
)==0 );
4819 return exprCodeInlineFunction(pParse
, pFarg
,
4820 SQLITE_PTR_TO_INT(pDef
->pUserData
), target
);
4821 }else if( pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
) ){
4822 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
4825 for(i
=0; i
<nFarg
; i
++){
4826 if( i
<32 && sqlite3ExprIsConstant(pFarg
->a
[i
].pExpr
) ){
4828 constMask
|= MASKBIT32(i
);
4830 if( (pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
)!=0 && !pColl
){
4831 pColl
= sqlite3ExprCollSeq(pParse
, pFarg
->a
[i
].pExpr
);
4836 r1
= pParse
->nMem
+1;
4837 pParse
->nMem
+= nFarg
;
4839 r1
= sqlite3GetTempRange(pParse
, nFarg
);
4842 /* For length() and typeof() and octet_length() functions,
4843 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4844 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid
4845 ** unnecessary data loading.
4847 if( (pDef
->funcFlags
& (SQLITE_FUNC_LENGTH
|SQLITE_FUNC_TYPEOF
))!=0 ){
4850 assert( pFarg
->a
[0].pExpr
!=0 );
4851 exprOp
= pFarg
->a
[0].pExpr
->op
;
4852 if( exprOp
==TK_COLUMN
|| exprOp
==TK_AGG_COLUMN
){
4853 assert( SQLITE_FUNC_LENGTH
==OPFLAG_LENGTHARG
);
4854 assert( SQLITE_FUNC_TYPEOF
==OPFLAG_TYPEOFARG
);
4855 assert( SQLITE_FUNC_BYTELEN
==OPFLAG_BYTELENARG
);
4856 assert( (OPFLAG_LENGTHARG
|OPFLAG_TYPEOFARG
)==OPFLAG_BYTELENARG
);
4857 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_LENGTHARG
);
4858 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_TYPEOFARG
);
4859 testcase( (pDef
->funcFlags
& OPFLAG_BYTELENARG
)==OPFLAG_BYTELENARG
);
4860 pFarg
->a
[0].pExpr
->op2
= pDef
->funcFlags
& OPFLAG_BYTELENARG
;
4864 sqlite3ExprCodeExprList(pParse
, pFarg
, r1
, 0, SQLITE_ECEL_FACTOR
);
4868 #ifndef SQLITE_OMIT_VIRTUALTABLE
4869 /* Possibly overload the function if the first argument is
4870 ** a virtual table column.
4872 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4873 ** second argument, not the first, as the argument to test to
4874 ** see if it is a column in a virtual table. This is done because
4875 ** the left operand of infix functions (the operand we want to
4876 ** control overloading) ends up as the second argument to the
4877 ** function. The expression "A glob B" is equivalent to
4878 ** "glob(B,A). We want to use the A in "A glob B" to test
4879 ** for function overloading. But we use the B term in "glob(B,A)".
4881 if( nFarg
>=2 && ExprHasProperty(pExpr
, EP_InfixFunc
) ){
4882 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[1].pExpr
);
4883 }else if( nFarg
>0 ){
4884 pDef
= sqlite3VtabOverloadFunction(db
, pDef
, nFarg
, pFarg
->a
[0].pExpr
);
4887 if( pDef
->funcFlags
& SQLITE_FUNC_NEEDCOLL
){
4888 if( !pColl
) pColl
= db
->pDfltColl
;
4889 sqlite3VdbeAddOp4(v
, OP_CollSeq
, 0, 0, 0, (char *)pColl
, P4_COLLSEQ
);
4891 sqlite3VdbeAddFunctionCall(pParse
, constMask
, r1
, target
, nFarg
,
4895 sqlite3ReleaseTempRange(pParse
, r1
, nFarg
);
4897 sqlite3VdbeReleaseRegisters(pParse
, r1
, nFarg
, constMask
, 1);
4902 #ifndef SQLITE_OMIT_SUBQUERY
4906 testcase( op
==TK_EXISTS
);
4907 testcase( op
==TK_SELECT
);
4908 if( pParse
->db
->mallocFailed
){
4910 }else if( op
==TK_SELECT
4911 && ALWAYS( ExprUseXSelect(pExpr
) )
4912 && (nCol
= pExpr
->x
.pSelect
->pEList
->nExpr
)!=1
4914 sqlite3SubselectError(pParse
, nCol
, 1);
4916 return sqlite3CodeSubselect(pParse
, pExpr
);
4920 case TK_SELECT_COLUMN
: {
4922 Expr
*pLeft
= pExpr
->pLeft
;
4923 if( pLeft
->iTable
==0 || pParse
->withinRJSubrtn
> pLeft
->op2
){
4924 pLeft
->iTable
= sqlite3CodeSubselect(pParse
, pLeft
);
4925 pLeft
->op2
= pParse
->withinRJSubrtn
;
4927 assert( pLeft
->op
==TK_SELECT
|| pLeft
->op
==TK_ERROR
);
4928 n
= sqlite3ExprVectorSize(pLeft
);
4929 if( pExpr
->iTable
!=n
){
4930 sqlite3ErrorMsg(pParse
, "%d columns assigned %d values",
4933 return pLeft
->iTable
+ pExpr
->iColumn
;
4936 int destIfFalse
= sqlite3VdbeMakeLabel(pParse
);
4937 int destIfNull
= sqlite3VdbeMakeLabel(pParse
);
4938 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
4939 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
4940 sqlite3VdbeAddOp2(v
, OP_Integer
, 1, target
);
4941 sqlite3VdbeResolveLabel(v
, destIfFalse
);
4942 sqlite3VdbeAddOp2(v
, OP_AddImm
, target
, 0);
4943 sqlite3VdbeResolveLabel(v
, destIfNull
);
4946 #endif /* SQLITE_OMIT_SUBQUERY */
4950 ** x BETWEEN y AND z
4952 ** This is equivalent to
4956 ** X is stored in pExpr->pLeft.
4957 ** Y is stored in pExpr->pList->a[0].pExpr.
4958 ** Z is stored in pExpr->pList->a[1].pExpr.
4961 exprCodeBetween(pParse
, pExpr
, target
, 0, 0);
4965 if( !ExprHasProperty(pExpr
, EP_Collate
) ){
4966 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
4967 ** "SOFT-COLLATE" that is added to constraints that are pushed down
4968 ** from outer queries into sub-queries by the push-down optimization.
4969 ** Clear subtypes as subtypes may not cross a subquery boundary.
4971 assert( pExpr
->pLeft
);
4972 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
4973 sqlite3VdbeAddOp1(v
, OP_ClrSubtype
, target
);
4976 pExpr
= pExpr
->pLeft
;
4977 goto expr_code_doover
; /* 2018-04-28: Prevent deep recursion. */
4982 pExpr
= pExpr
->pLeft
;
4983 goto expr_code_doover
; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4987 /* If the opcode is TK_TRIGGER, then the expression is a reference
4988 ** to a column in the new.* or old.* pseudo-tables available to
4989 ** trigger programs. In this case Expr.iTable is set to 1 for the
4990 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4991 ** is set to the column of the pseudo-table to read, or to -1 to
4992 ** read the rowid field.
4994 ** The expression is implemented using an OP_Param opcode. The p1
4995 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4996 ** to reference another column of the old.* pseudo-table, where
4997 ** i is the index of the column. For a new.rowid reference, p1 is
4998 ** set to (n+1), where n is the number of columns in each pseudo-table.
4999 ** For a reference to any other column in the new.* pseudo-table, p1
5000 ** is set to (n+2+i), where n and i are as defined previously. For
5001 ** example, if the table on which triggers are being fired is
5004 ** CREATE TABLE t1(a, b);
5006 ** Then p1 is interpreted as follows:
5008 ** p1==0 -> old.rowid p1==3 -> new.rowid
5009 ** p1==1 -> old.a p1==4 -> new.a
5010 ** p1==2 -> old.b p1==5 -> new.b
5016 assert( ExprUseYTab(pExpr
) );
5017 pTab
= pExpr
->y
.pTab
;
5018 iCol
= pExpr
->iColumn
;
5019 p1
= pExpr
->iTable
* (pTab
->nCol
+1) + 1
5020 + sqlite3TableColumnToStorage(pTab
, iCol
);
5022 assert( pExpr
->iTable
==0 || pExpr
->iTable
==1 );
5023 assert( iCol
>=-1 && iCol
<pTab
->nCol
);
5024 assert( pTab
->iPKey
<0 || iCol
!=pTab
->iPKey
);
5025 assert( p1
>=0 && p1
<(pTab
->nCol
*2+2) );
5027 sqlite3VdbeAddOp2(v
, OP_Param
, p1
, target
);
5028 VdbeComment((v
, "r[%d]=%s.%s", target
,
5029 (pExpr
->iTable
? "new" : "old"),
5030 (pExpr
->iColumn
<0 ? "rowid" : pExpr
->y
.pTab
->aCol
[iCol
].zCnName
)
5033 #ifndef SQLITE_OMIT_FLOATING_POINT
5034 /* If the column has REAL affinity, it may currently be stored as an
5035 ** integer. Use OP_RealAffinity to make sure it is really real.
5037 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
5038 ** floating point when extracting it from the record. */
5039 if( iCol
>=0 && pTab
->aCol
[iCol
].affinity
==SQLITE_AFF_REAL
){
5040 sqlite3VdbeAddOp1(v
, OP_RealAffinity
, target
);
5047 sqlite3ErrorMsg(pParse
, "row value misused");
5051 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
5052 ** that derive from the right-hand table of a LEFT JOIN. The
5053 ** Expr.iTable value is the table number for the right-hand table.
5054 ** The expression is only evaluated if that table is not currently
5055 ** on a LEFT JOIN NULL row.
5057 case TK_IF_NULL_ROW
: {
5059 u8 okConstFactor
= pParse
->okConstFactor
;
5060 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
5062 assert( pExpr
->iAgg
>=0 && pExpr
->iAgg
<pAggInfo
->nColumn
);
5063 if( !pAggInfo
->directMode
){
5064 inReg
= AggInfoColumnReg(pAggInfo
, pExpr
->iAgg
);
5067 if( pExpr
->pAggInfo
->useSortingIdx
){
5068 sqlite3VdbeAddOp3(v
, OP_Column
, pAggInfo
->sortingIdxPTab
,
5069 pAggInfo
->aCol
[pExpr
->iAgg
].iSorterColumn
,
5075 addrINR
= sqlite3VdbeAddOp3(v
, OP_IfNullRow
, pExpr
->iTable
, 0, target
);
5076 /* The OP_IfNullRow opcode above can overwrite the result register with
5077 ** NULL. So we have to ensure that the result register is not a value
5078 ** that is suppose to be a constant. Two defenses are needed:
5079 ** (1) Temporarily disable factoring of constant expressions
5080 ** (2) Make sure the computed value really is stored in register
5081 ** "target" and not someplace else.
5083 pParse
->okConstFactor
= 0; /* note (1) above */
5084 sqlite3ExprCode(pParse
, pExpr
->pLeft
, target
);
5085 assert( target
==inReg
);
5086 pParse
->okConstFactor
= okConstFactor
;
5087 sqlite3VdbeJumpHere(v
, addrINR
);
5093 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5096 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5098 ** Form A is can be transformed into the equivalent form B as follows:
5099 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
5100 ** WHEN x=eN THEN rN ELSE y END
5102 ** X (if it exists) is in pExpr->pLeft.
5103 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
5104 ** odd. The Y is also optional. If the number of elements in x.pList
5105 ** is even, then Y is omitted and the "otherwise" result is NULL.
5106 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
5108 ** The result of the expression is the Ri for the first matching Ei,
5109 ** or if there is no matching Ei, the ELSE term Y, or if there is
5110 ** no ELSE term, NULL.
5113 int endLabel
; /* GOTO label for end of CASE stmt */
5114 int nextCase
; /* GOTO label for next WHEN clause */
5115 int nExpr
; /* 2x number of WHEN terms */
5116 int i
; /* Loop counter */
5117 ExprList
*pEList
; /* List of WHEN terms */
5118 struct ExprList_item
*aListelem
; /* Array of WHEN terms */
5119 Expr opCompare
; /* The X==Ei expression */
5120 Expr
*pX
; /* The X expression */
5121 Expr
*pTest
= 0; /* X==Ei (form A) or just Ei (form B) */
5123 sqlite3
*db
= pParse
->db
;
5125 assert( ExprUseXList(pExpr
) && pExpr
->x
.pList
!=0 );
5126 assert(pExpr
->x
.pList
->nExpr
> 0);
5127 pEList
= pExpr
->x
.pList
;
5128 aListelem
= pEList
->a
;
5129 nExpr
= pEList
->nExpr
;
5130 endLabel
= sqlite3VdbeMakeLabel(pParse
);
5131 if( (pX
= pExpr
->pLeft
)!=0 ){
5132 pDel
= sqlite3ExprDup(db
, pX
, 0);
5133 if( db
->mallocFailed
){
5134 sqlite3ExprDelete(db
, pDel
);
5137 testcase( pX
->op
==TK_COLUMN
);
5138 exprToRegister(pDel
, exprCodeVector(pParse
, pDel
, ®Free1
));
5139 testcase( regFree1
==0 );
5140 memset(&opCompare
, 0, sizeof(opCompare
));
5141 opCompare
.op
= TK_EQ
;
5142 opCompare
.pLeft
= pDel
;
5144 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
5145 ** The value in regFree1 might get SCopy-ed into the file result.
5146 ** So make sure that the regFree1 register is not reused for other
5147 ** purposes and possibly overwritten. */
5150 for(i
=0; i
<nExpr
-1; i
=i
+2){
5153 opCompare
.pRight
= aListelem
[i
].pExpr
;
5155 pTest
= aListelem
[i
].pExpr
;
5157 nextCase
= sqlite3VdbeMakeLabel(pParse
);
5158 testcase( pTest
->op
==TK_COLUMN
);
5159 sqlite3ExprIfFalse(pParse
, pTest
, nextCase
, SQLITE_JUMPIFNULL
);
5160 testcase( aListelem
[i
+1].pExpr
->op
==TK_COLUMN
);
5161 sqlite3ExprCode(pParse
, aListelem
[i
+1].pExpr
, target
);
5162 sqlite3VdbeGoto(v
, endLabel
);
5163 sqlite3VdbeResolveLabel(v
, nextCase
);
5166 sqlite3ExprCode(pParse
, pEList
->a
[nExpr
-1].pExpr
, target
);
5168 sqlite3VdbeAddOp2(v
, OP_Null
, 0, target
);
5170 sqlite3ExprDelete(db
, pDel
);
5171 setDoNotMergeFlagOnCopy(v
);
5172 sqlite3VdbeResolveLabel(v
, endLabel
);
5175 #ifndef SQLITE_OMIT_TRIGGER
5177 assert( pExpr
->affExpr
==OE_Rollback
5178 || pExpr
->affExpr
==OE_Abort
5179 || pExpr
->affExpr
==OE_Fail
5180 || pExpr
->affExpr
==OE_Ignore
5182 if( !pParse
->pTriggerTab
&& !pParse
->nested
){
5183 sqlite3ErrorMsg(pParse
,
5184 "RAISE() may only be used within a trigger-program");
5187 if( pExpr
->affExpr
==OE_Abort
){
5188 sqlite3MayAbort(pParse
);
5190 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
5191 if( pExpr
->affExpr
==OE_Ignore
){
5193 v
, OP_Halt
, SQLITE_OK
, OE_Ignore
, 0, pExpr
->u
.zToken
,0);
5196 sqlite3HaltConstraint(pParse
,
5197 pParse
->pTriggerTab
? SQLITE_CONSTRAINT_TRIGGER
: SQLITE_ERROR
,
5198 pExpr
->affExpr
, pExpr
->u
.zToken
, 0, 0);
5205 sqlite3ReleaseTempReg(pParse
, regFree1
);
5206 sqlite3ReleaseTempReg(pParse
, regFree2
);
5211 ** Generate code that will evaluate expression pExpr just one time
5212 ** per prepared statement execution.
5214 ** If the expression uses functions (that might throw an exception) then
5215 ** guard them with an OP_Once opcode to ensure that the code is only executed
5216 ** once. If no functions are involved, then factor the code out and put it at
5217 ** the end of the prepared statement in the initialization section.
5219 ** If regDest>0 then the result is always stored in that register and the
5220 ** result is not reusable. If regDest<0 then this routine is free to
5221 ** store the value wherever it wants. The register where the expression
5222 ** is stored is returned. When regDest<0, two identical expressions might
5223 ** code to the same register, if they do not contain function calls and hence
5224 ** are factored out into the initialization section at the end of the
5225 ** prepared statement.
5227 int sqlite3ExprCodeRunJustOnce(
5228 Parse
*pParse
, /* Parsing context */
5229 Expr
*pExpr
, /* The expression to code when the VDBE initializes */
5230 int regDest
/* Store the value in this register */
5233 assert( ConstFactorOk(pParse
) );
5234 assert( regDest
!=0 );
5235 p
= pParse
->pConstExpr
;
5236 if( regDest
<0 && p
){
5237 struct ExprList_item
*pItem
;
5239 for(pItem
=p
->a
, i
=p
->nExpr
; i
>0; pItem
++, i
--){
5240 if( pItem
->fg
.reusable
5241 && sqlite3ExprCompare(0,pItem
->pExpr
,pExpr
,-1)==0
5243 return pItem
->u
.iConstExprReg
;
5247 pExpr
= sqlite3ExprDup(pParse
->db
, pExpr
, 0);
5248 if( pExpr
!=0 && ExprHasProperty(pExpr
, EP_HasFunc
) ){
5249 Vdbe
*v
= pParse
->pVdbe
;
5252 addr
= sqlite3VdbeAddOp0(v
, OP_Once
); VdbeCoverage(v
);
5253 pParse
->okConstFactor
= 0;
5254 if( !pParse
->db
->mallocFailed
){
5255 if( regDest
<0 ) regDest
= ++pParse
->nMem
;
5256 sqlite3ExprCode(pParse
, pExpr
, regDest
);
5258 pParse
->okConstFactor
= 1;
5259 sqlite3ExprDelete(pParse
->db
, pExpr
);
5260 sqlite3VdbeJumpHere(v
, addr
);
5262 p
= sqlite3ExprListAppend(pParse
, p
, pExpr
);
5264 struct ExprList_item
*pItem
= &p
->a
[p
->nExpr
-1];
5265 pItem
->fg
.reusable
= regDest
<0;
5266 if( regDest
<0 ) regDest
= ++pParse
->nMem
;
5267 pItem
->u
.iConstExprReg
= regDest
;
5269 pParse
->pConstExpr
= p
;
5275 ** Generate code to evaluate an expression and store the results
5276 ** into a register. Return the register number where the results
5279 ** If the register is a temporary register that can be deallocated,
5280 ** then write its number into *pReg. If the result register is not
5281 ** a temporary, then set *pReg to zero.
5283 ** If pExpr is a constant, then this routine might generate this
5284 ** code to fill the register in the initialization section of the
5285 ** VDBE program, in order to factor it out of the evaluation loop.
5287 int sqlite3ExprCodeTemp(Parse
*pParse
, Expr
*pExpr
, int *pReg
){
5289 pExpr
= sqlite3ExprSkipCollateAndLikely(pExpr
);
5290 if( ConstFactorOk(pParse
)
5292 && pExpr
->op
!=TK_REGISTER
5293 && sqlite3ExprIsConstantNotJoin(pExpr
)
5296 r2
= sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, -1);
5298 int r1
= sqlite3GetTempReg(pParse
);
5299 r2
= sqlite3ExprCodeTarget(pParse
, pExpr
, r1
);
5303 sqlite3ReleaseTempReg(pParse
, r1
);
5311 ** Generate code that will evaluate expression pExpr and store the
5312 ** results in register target. The results are guaranteed to appear
5313 ** in register target.
5315 void sqlite3ExprCode(Parse
*pParse
, Expr
*pExpr
, int target
){
5318 assert( pExpr
==0 || !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
5319 assert( target
>0 && target
<=pParse
->nMem
);
5320 assert( pParse
->pVdbe
!=0 || pParse
->db
->mallocFailed
);
5321 if( pParse
->pVdbe
==0 ) return;
5322 inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
);
5323 if( inReg
!=target
){
5326 && (ExprHasProperty(pExpr
,EP_Subquery
) || pExpr
->op
==TK_REGISTER
)
5332 sqlite3VdbeAddOp2(pParse
->pVdbe
, op
, inReg
, target
);
5337 ** Make a transient copy of expression pExpr and then code it using
5338 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5339 ** except that the input expression is guaranteed to be unchanged.
5341 void sqlite3ExprCodeCopy(Parse
*pParse
, Expr
*pExpr
, int target
){
5342 sqlite3
*db
= pParse
->db
;
5343 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
5344 if( !db
->mallocFailed
) sqlite3ExprCode(pParse
, pExpr
, target
);
5345 sqlite3ExprDelete(db
, pExpr
);
5349 ** Generate code that will evaluate expression pExpr and store the
5350 ** results in register target. The results are guaranteed to appear
5351 ** in register target. If the expression is constant, then this routine
5352 ** might choose to code the expression at initialization time.
5354 void sqlite3ExprCodeFactorable(Parse
*pParse
, Expr
*pExpr
, int target
){
5355 if( pParse
->okConstFactor
&& sqlite3ExprIsConstantNotJoin(pExpr
) ){
5356 sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, target
);
5358 sqlite3ExprCodeCopy(pParse
, pExpr
, target
);
5363 ** Generate code that pushes the value of every element of the given
5364 ** expression list into a sequence of registers beginning at target.
5366 ** Return the number of elements evaluated. The number returned will
5367 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5370 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5371 ** filled using OP_SCopy. OP_Copy must be used instead.
5373 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5374 ** factored out into initialization code.
5376 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5377 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5378 ** in registers at srcReg, and so the value can be copied from there.
5379 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5380 ** are simply omitted rather than being copied from srcReg.
5382 int sqlite3ExprCodeExprList(
5383 Parse
*pParse
, /* Parsing context */
5384 ExprList
*pList
, /* The expression list to be coded */
5385 int target
, /* Where to write results */
5386 int srcReg
, /* Source registers if SQLITE_ECEL_REF */
5387 u8 flags
/* SQLITE_ECEL_* flags */
5389 struct ExprList_item
*pItem
;
5391 u8 copyOp
= (flags
& SQLITE_ECEL_DUP
) ? OP_Copy
: OP_SCopy
;
5392 Vdbe
*v
= pParse
->pVdbe
;
5395 assert( pParse
->pVdbe
!=0 ); /* Never gets this far otherwise */
5397 if( !ConstFactorOk(pParse
) ) flags
&= ~SQLITE_ECEL_FACTOR
;
5398 for(pItem
=pList
->a
, i
=0; i
<n
; i
++, pItem
++){
5399 Expr
*pExpr
= pItem
->pExpr
;
5400 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5401 if( pItem
->fg
.bSorterRef
){
5406 if( (flags
& SQLITE_ECEL_REF
)!=0 && (j
= pItem
->u
.x
.iOrderByCol
)>0 ){
5407 if( flags
& SQLITE_ECEL_OMITREF
){
5411 sqlite3VdbeAddOp2(v
, copyOp
, j
+srcReg
-1, target
+i
);
5413 }else if( (flags
& SQLITE_ECEL_FACTOR
)!=0
5414 && sqlite3ExprIsConstantNotJoin(pExpr
)
5416 sqlite3ExprCodeRunJustOnce(pParse
, pExpr
, target
+i
);
5418 int inReg
= sqlite3ExprCodeTarget(pParse
, pExpr
, target
+i
);
5419 if( inReg
!=target
+i
){
5422 && (pOp
=sqlite3VdbeGetLastOp(v
))->opcode
==OP_Copy
5423 && pOp
->p1
+pOp
->p3
+1==inReg
5424 && pOp
->p2
+pOp
->p3
+1==target
+i
5425 && pOp
->p5
==0 /* The do-not-merge flag must be clear */
5429 sqlite3VdbeAddOp2(v
, copyOp
, inReg
, target
+i
);
5438 ** Generate code for a BETWEEN operator.
5440 ** x BETWEEN y AND z
5442 ** The above is equivalent to
5446 ** Code it as such, taking care to do the common subexpression
5447 ** elimination of x.
5449 ** The xJumpIf parameter determines details:
5451 ** NULL: Store the boolean result in reg[dest]
5452 ** sqlite3ExprIfTrue: Jump to dest if true
5453 ** sqlite3ExprIfFalse: Jump to dest if false
5455 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5457 static void exprCodeBetween(
5458 Parse
*pParse
, /* Parsing and code generating context */
5459 Expr
*pExpr
, /* The BETWEEN expression */
5460 int dest
, /* Jump destination or storage location */
5461 void (*xJump
)(Parse
*,Expr
*,int,int), /* Action to take */
5462 int jumpIfNull
/* Take the jump if the BETWEEN is NULL */
5464 Expr exprAnd
; /* The AND operator in x>=y AND x<=z */
5465 Expr compLeft
; /* The x>=y term */
5466 Expr compRight
; /* The x<=z term */
5467 int regFree1
= 0; /* Temporary use register */
5469 sqlite3
*db
= pParse
->db
;
5471 memset(&compLeft
, 0, sizeof(Expr
));
5472 memset(&compRight
, 0, sizeof(Expr
));
5473 memset(&exprAnd
, 0, sizeof(Expr
));
5475 assert( ExprUseXList(pExpr
) );
5476 pDel
= sqlite3ExprDup(db
, pExpr
->pLeft
, 0);
5477 if( db
->mallocFailed
==0 ){
5478 exprAnd
.op
= TK_AND
;
5479 exprAnd
.pLeft
= &compLeft
;
5480 exprAnd
.pRight
= &compRight
;
5481 compLeft
.op
= TK_GE
;
5482 compLeft
.pLeft
= pDel
;
5483 compLeft
.pRight
= pExpr
->x
.pList
->a
[0].pExpr
;
5484 compRight
.op
= TK_LE
;
5485 compRight
.pLeft
= pDel
;
5486 compRight
.pRight
= pExpr
->x
.pList
->a
[1].pExpr
;
5487 exprToRegister(pDel
, exprCodeVector(pParse
, pDel
, ®Free1
));
5489 xJump(pParse
, &exprAnd
, dest
, jumpIfNull
);
5491 /* Mark the expression is being from the ON or USING clause of a join
5492 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5493 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5494 ** for clarity, but we are out of bits in the Expr.flags field so we
5495 ** have to reuse the EP_OuterON bit. Bummer. */
5496 pDel
->flags
|= EP_OuterON
;
5497 sqlite3ExprCodeTarget(pParse
, &exprAnd
, dest
);
5499 sqlite3ReleaseTempReg(pParse
, regFree1
);
5501 sqlite3ExprDelete(db
, pDel
);
5503 /* Ensure adequate test coverage */
5504 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
==0 && regFree1
==0 );
5505 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
==0 && regFree1
!=0 );
5506 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
!=0 && regFree1
==0 );
5507 testcase( xJump
==sqlite3ExprIfTrue
&& jumpIfNull
!=0 && regFree1
!=0 );
5508 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
==0 && regFree1
==0 );
5509 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
==0 && regFree1
!=0 );
5510 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
!=0 && regFree1
==0 );
5511 testcase( xJump
==sqlite3ExprIfFalse
&& jumpIfNull
!=0 && regFree1
!=0 );
5512 testcase( xJump
==0 );
5516 ** Generate code for a boolean expression such that a jump is made
5517 ** to the label "dest" if the expression is true but execution
5518 ** continues straight thru if the expression is false.
5520 ** If the expression evaluates to NULL (neither true nor false), then
5521 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5523 ** This code depends on the fact that certain token values (ex: TK_EQ)
5524 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5525 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5526 ** the make process cause these values to align. Assert()s in the code
5527 ** below verify that the numbers are aligned correctly.
5529 void sqlite3ExprIfTrue(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
5530 Vdbe
*v
= pParse
->pVdbe
;
5536 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
5537 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
5538 if( NEVER(pExpr
==0) ) return; /* No way this can happen */
5539 assert( !ExprHasVVAProperty(pExpr
, EP_Immutable
) );
5544 Expr
*pAlt
= sqlite3ExprSimplifiedAndOr(pExpr
);
5546 sqlite3ExprIfTrue(pParse
, pAlt
, dest
, jumpIfNull
);
5547 }else if( op
==TK_AND
){
5548 int d2
= sqlite3VdbeMakeLabel(pParse
);
5549 testcase( jumpIfNull
==0 );
5550 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, d2
,
5551 jumpIfNull
^SQLITE_JUMPIFNULL
);
5552 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5553 sqlite3VdbeResolveLabel(v
, d2
);
5555 testcase( jumpIfNull
==0 );
5556 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5557 sqlite3ExprIfTrue(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5562 testcase( jumpIfNull
==0 );
5563 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5567 int isNot
; /* IS NOT TRUE or IS NOT FALSE */
5568 int isTrue
; /* IS TRUE or IS NOT TRUE */
5569 testcase( jumpIfNull
==0 );
5570 isNot
= pExpr
->op2
==TK_ISNOT
;
5571 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
5572 testcase( isTrue
&& isNot
);
5573 testcase( !isTrue
&& isNot
);
5574 if( isTrue
^ isNot
){
5575 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
,
5576 isNot
? SQLITE_JUMPIFNULL
: 0);
5578 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
,
5579 isNot
? SQLITE_JUMPIFNULL
: 0);
5585 testcase( op
==TK_IS
);
5586 testcase( op
==TK_ISNOT
);
5587 op
= (op
==TK_IS
) ? TK_EQ
: TK_NE
;
5588 jumpIfNull
= SQLITE_NULLEQ
;
5589 /* no break */ deliberate_fall_through
5596 if( sqlite3ExprIsVector(pExpr
->pLeft
) ) goto default_expr
;
5597 testcase( jumpIfNull
==0 );
5598 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5599 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
5600 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
5601 r1
, r2
, dest
, jumpIfNull
, ExprHasProperty(pExpr
,EP_Commuted
));
5602 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
5603 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
5604 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
5605 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
5606 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
);
5607 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
==SQLITE_NULLEQ
);
5608 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
!=SQLITE_NULLEQ
);
5609 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
);
5610 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
==SQLITE_NULLEQ
);
5611 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
!=SQLITE_NULLEQ
);
5612 testcase( regFree1
==0 );
5613 testcase( regFree2
==0 );
5618 assert( TK_ISNULL
==OP_IsNull
); testcase( op
==TK_ISNULL
);
5619 assert( TK_NOTNULL
==OP_NotNull
); testcase( op
==TK_NOTNULL
);
5620 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5621 sqlite3VdbeTypeofColumn(v
, r1
);
5622 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
5623 VdbeCoverageIf(v
, op
==TK_ISNULL
);
5624 VdbeCoverageIf(v
, op
==TK_NOTNULL
);
5625 testcase( regFree1
==0 );
5629 testcase( jumpIfNull
==0 );
5630 exprCodeBetween(pParse
, pExpr
, dest
, sqlite3ExprIfTrue
, jumpIfNull
);
5633 #ifndef SQLITE_OMIT_SUBQUERY
5635 int destIfFalse
= sqlite3VdbeMakeLabel(pParse
);
5636 int destIfNull
= jumpIfNull
? dest
: destIfFalse
;
5637 sqlite3ExprCodeIN(pParse
, pExpr
, destIfFalse
, destIfNull
);
5638 sqlite3VdbeGoto(v
, dest
);
5639 sqlite3VdbeResolveLabel(v
, destIfFalse
);
5645 if( ExprAlwaysTrue(pExpr
) ){
5646 sqlite3VdbeGoto(v
, dest
);
5647 }else if( ExprAlwaysFalse(pExpr
) ){
5650 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
5651 sqlite3VdbeAddOp3(v
, OP_If
, r1
, dest
, jumpIfNull
!=0);
5653 testcase( regFree1
==0 );
5654 testcase( jumpIfNull
==0 );
5659 sqlite3ReleaseTempReg(pParse
, regFree1
);
5660 sqlite3ReleaseTempReg(pParse
, regFree2
);
5664 ** Generate code for a boolean expression such that a jump is made
5665 ** to the label "dest" if the expression is false but execution
5666 ** continues straight thru if the expression is true.
5668 ** If the expression evaluates to NULL (neither true nor false) then
5669 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5672 void sqlite3ExprIfFalse(Parse
*pParse
, Expr
*pExpr
, int dest
, int jumpIfNull
){
5673 Vdbe
*v
= pParse
->pVdbe
;
5679 assert( jumpIfNull
==SQLITE_JUMPIFNULL
|| jumpIfNull
==0 );
5680 if( NEVER(v
==0) ) return; /* Existence of VDBE checked by caller */
5681 if( pExpr
==0 ) return;
5682 assert( !ExprHasVVAProperty(pExpr
,EP_Immutable
) );
5684 /* The value of pExpr->op and op are related as follows:
5687 ** --------- ----------
5688 ** TK_ISNULL OP_NotNull
5689 ** TK_NOTNULL OP_IsNull
5697 ** For other values of pExpr->op, op is undefined and unused.
5698 ** The value of TK_ and OP_ constants are arranged such that we
5699 ** can compute the mapping above using the following expression.
5700 ** Assert()s verify that the computation is correct.
5702 op
= ((pExpr
->op
+(TK_ISNULL
&1))^1)-(TK_ISNULL
&1);
5704 /* Verify correct alignment of TK_ and OP_ constants
5706 assert( pExpr
->op
!=TK_ISNULL
|| op
==OP_NotNull
);
5707 assert( pExpr
->op
!=TK_NOTNULL
|| op
==OP_IsNull
);
5708 assert( pExpr
->op
!=TK_NE
|| op
==OP_Eq
);
5709 assert( pExpr
->op
!=TK_EQ
|| op
==OP_Ne
);
5710 assert( pExpr
->op
!=TK_LT
|| op
==OP_Ge
);
5711 assert( pExpr
->op
!=TK_LE
|| op
==OP_Gt
);
5712 assert( pExpr
->op
!=TK_GT
|| op
==OP_Le
);
5713 assert( pExpr
->op
!=TK_GE
|| op
==OP_Lt
);
5715 switch( pExpr
->op
){
5718 Expr
*pAlt
= sqlite3ExprSimplifiedAndOr(pExpr
);
5720 sqlite3ExprIfFalse(pParse
, pAlt
, dest
, jumpIfNull
);
5721 }else if( pExpr
->op
==TK_AND
){
5722 testcase( jumpIfNull
==0 );
5723 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5724 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5726 int d2
= sqlite3VdbeMakeLabel(pParse
);
5727 testcase( jumpIfNull
==0 );
5728 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, d2
,
5729 jumpIfNull
^SQLITE_JUMPIFNULL
);
5730 sqlite3ExprIfFalse(pParse
, pExpr
->pRight
, dest
, jumpIfNull
);
5731 sqlite3VdbeResolveLabel(v
, d2
);
5736 testcase( jumpIfNull
==0 );
5737 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
, jumpIfNull
);
5741 int isNot
; /* IS NOT TRUE or IS NOT FALSE */
5742 int isTrue
; /* IS TRUE or IS NOT TRUE */
5743 testcase( jumpIfNull
==0 );
5744 isNot
= pExpr
->op2
==TK_ISNOT
;
5745 isTrue
= sqlite3ExprTruthValue(pExpr
->pRight
);
5746 testcase( isTrue
&& isNot
);
5747 testcase( !isTrue
&& isNot
);
5748 if( isTrue
^ isNot
){
5749 /* IS TRUE and IS NOT FALSE */
5750 sqlite3ExprIfFalse(pParse
, pExpr
->pLeft
, dest
,
5751 isNot
? 0 : SQLITE_JUMPIFNULL
);
5754 /* IS FALSE and IS NOT TRUE */
5755 sqlite3ExprIfTrue(pParse
, pExpr
->pLeft
, dest
,
5756 isNot
? 0 : SQLITE_JUMPIFNULL
);
5762 testcase( pExpr
->op
==TK_IS
);
5763 testcase( pExpr
->op
==TK_ISNOT
);
5764 op
= (pExpr
->op
==TK_IS
) ? TK_NE
: TK_EQ
;
5765 jumpIfNull
= SQLITE_NULLEQ
;
5766 /* no break */ deliberate_fall_through
5773 if( sqlite3ExprIsVector(pExpr
->pLeft
) ) goto default_expr
;
5774 testcase( jumpIfNull
==0 );
5775 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5776 r2
= sqlite3ExprCodeTemp(pParse
, pExpr
->pRight
, ®Free2
);
5777 codeCompare(pParse
, pExpr
->pLeft
, pExpr
->pRight
, op
,
5778 r1
, r2
, dest
, jumpIfNull
,ExprHasProperty(pExpr
,EP_Commuted
));
5779 assert(TK_LT
==OP_Lt
); testcase(op
==OP_Lt
); VdbeCoverageIf(v
,op
==OP_Lt
);
5780 assert(TK_LE
==OP_Le
); testcase(op
==OP_Le
); VdbeCoverageIf(v
,op
==OP_Le
);
5781 assert(TK_GT
==OP_Gt
); testcase(op
==OP_Gt
); VdbeCoverageIf(v
,op
==OP_Gt
);
5782 assert(TK_GE
==OP_Ge
); testcase(op
==OP_Ge
); VdbeCoverageIf(v
,op
==OP_Ge
);
5783 assert(TK_EQ
==OP_Eq
); testcase(op
==OP_Eq
);
5784 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
!=SQLITE_NULLEQ
);
5785 VdbeCoverageIf(v
, op
==OP_Eq
&& jumpIfNull
==SQLITE_NULLEQ
);
5786 assert(TK_NE
==OP_Ne
); testcase(op
==OP_Ne
);
5787 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
!=SQLITE_NULLEQ
);
5788 VdbeCoverageIf(v
, op
==OP_Ne
&& jumpIfNull
==SQLITE_NULLEQ
);
5789 testcase( regFree1
==0 );
5790 testcase( regFree2
==0 );
5795 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
->pLeft
, ®Free1
);
5796 sqlite3VdbeTypeofColumn(v
, r1
);
5797 sqlite3VdbeAddOp2(v
, op
, r1
, dest
);
5798 testcase( op
==TK_ISNULL
); VdbeCoverageIf(v
, op
==TK_ISNULL
);
5799 testcase( op
==TK_NOTNULL
); VdbeCoverageIf(v
, op
==TK_NOTNULL
);
5800 testcase( regFree1
==0 );
5804 testcase( jumpIfNull
==0 );
5805 exprCodeBetween(pParse
, pExpr
, dest
, sqlite3ExprIfFalse
, jumpIfNull
);
5808 #ifndef SQLITE_OMIT_SUBQUERY
5811 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, dest
);
5813 int destIfNull
= sqlite3VdbeMakeLabel(pParse
);
5814 sqlite3ExprCodeIN(pParse
, pExpr
, dest
, destIfNull
);
5815 sqlite3VdbeResolveLabel(v
, destIfNull
);
5822 if( ExprAlwaysFalse(pExpr
) ){
5823 sqlite3VdbeGoto(v
, dest
);
5824 }else if( ExprAlwaysTrue(pExpr
) ){
5827 r1
= sqlite3ExprCodeTemp(pParse
, pExpr
, ®Free1
);
5828 sqlite3VdbeAddOp3(v
, OP_IfNot
, r1
, dest
, jumpIfNull
!=0);
5830 testcase( regFree1
==0 );
5831 testcase( jumpIfNull
==0 );
5836 sqlite3ReleaseTempReg(pParse
, regFree1
);
5837 sqlite3ReleaseTempReg(pParse
, regFree2
);
5841 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5842 ** code generation, and that copy is deleted after code generation. This
5843 ** ensures that the original pExpr is unchanged.
5845 void sqlite3ExprIfFalseDup(Parse
*pParse
, Expr
*pExpr
, int dest
,int jumpIfNull
){
5846 sqlite3
*db
= pParse
->db
;
5847 Expr
*pCopy
= sqlite3ExprDup(db
, pExpr
, 0);
5848 if( db
->mallocFailed
==0 ){
5849 sqlite3ExprIfFalse(pParse
, pCopy
, dest
, jumpIfNull
);
5851 sqlite3ExprDelete(db
, pCopy
);
5855 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5856 ** type of expression.
5858 ** If pExpr is a simple SQL value - an integer, real, string, blob
5859 ** or NULL value - then the VDBE currently being prepared is configured
5860 ** to re-prepare each time a new value is bound to variable pVar.
5862 ** Additionally, if pExpr is a simple SQL value and the value is the
5863 ** same as that currently bound to variable pVar, non-zero is returned.
5864 ** Otherwise, if the values are not the same or if pExpr is not a simple
5865 ** SQL value, zero is returned.
5867 static int exprCompareVariable(
5868 const Parse
*pParse
,
5874 sqlite3_value
*pL
, *pR
= 0;
5876 sqlite3ValueFromExpr(pParse
->db
, pExpr
, SQLITE_UTF8
, SQLITE_AFF_BLOB
, &pR
);
5878 iVar
= pVar
->iColumn
;
5879 sqlite3VdbeSetVarmask(pParse
->pVdbe
, iVar
);
5880 pL
= sqlite3VdbeGetBoundValue(pParse
->pReprepare
, iVar
, SQLITE_AFF_BLOB
);
5882 if( sqlite3_value_type(pL
)==SQLITE_TEXT
){
5883 sqlite3_value_text(pL
); /* Make sure the encoding is UTF-8 */
5885 res
= 0==sqlite3MemCompare(pL
, pR
, 0);
5887 sqlite3ValueFree(pR
);
5888 sqlite3ValueFree(pL
);
5895 ** Do a deep comparison of two expression trees. Return 0 if the two
5896 ** expressions are completely identical. Return 1 if they differ only
5897 ** by a COLLATE operator at the top level. Return 2 if there are differences
5898 ** other than the top-level COLLATE operator.
5900 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5901 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5903 ** The pA side might be using TK_REGISTER. If that is the case and pB is
5904 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5906 ** Sometimes this routine will return 2 even if the two expressions
5907 ** really are equivalent. If we cannot prove that the expressions are
5908 ** identical, we return 2 just to be safe. So if this routine
5909 ** returns 2, then you do not really know for certain if the two
5910 ** expressions are the same. But if you get a 0 or 1 return, then you
5911 ** can be sure the expressions are the same. In the places where
5912 ** this routine is used, it does not hurt to get an extra 2 - that
5913 ** just might result in some slightly slower code. But returning
5914 ** an incorrect 0 or 1 could lead to a malfunction.
5916 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5917 ** pParse->pReprepare can be matched against literals in pB. The
5918 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5919 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5920 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5921 ** pB causes a return value of 2.
5923 int sqlite3ExprCompare(
5924 const Parse
*pParse
,
5930 if( pA
==0 || pB
==0 ){
5931 return pB
==pA
? 0 : 2;
5933 if( pParse
&& pA
->op
==TK_VARIABLE
&& exprCompareVariable(pParse
, pA
, pB
) ){
5936 combinedFlags
= pA
->flags
| pB
->flags
;
5937 if( combinedFlags
& EP_IntValue
){
5938 if( (pA
->flags
&pB
->flags
&EP_IntValue
)!=0 && pA
->u
.iValue
==pB
->u
.iValue
){
5943 if( pA
->op
!=pB
->op
|| pA
->op
==TK_RAISE
){
5944 if( pA
->op
==TK_COLLATE
&& sqlite3ExprCompare(pParse
, pA
->pLeft
,pB
,iTab
)<2 ){
5947 if( pB
->op
==TK_COLLATE
&& sqlite3ExprCompare(pParse
, pA
,pB
->pLeft
,iTab
)<2 ){
5950 if( pA
->op
==TK_AGG_COLUMN
&& pB
->op
==TK_COLUMN
5951 && pB
->iTable
<0 && pA
->iTable
==iTab
5958 assert( !ExprHasProperty(pA
, EP_IntValue
) );
5959 assert( !ExprHasProperty(pB
, EP_IntValue
) );
5961 if( pA
->op
==TK_FUNCTION
|| pA
->op
==TK_AGG_FUNCTION
){
5962 if( sqlite3StrICmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ) return 2;
5963 #ifndef SQLITE_OMIT_WINDOWFUNC
5964 assert( pA
->op
==pB
->op
);
5965 if( ExprHasProperty(pA
,EP_WinFunc
)!=ExprHasProperty(pB
,EP_WinFunc
) ){
5968 if( ExprHasProperty(pA
,EP_WinFunc
) ){
5969 if( sqlite3WindowCompare(pParse
, pA
->y
.pWin
, pB
->y
.pWin
, 1)!=0 ){
5974 }else if( pA
->op
==TK_NULL
){
5976 }else if( pA
->op
==TK_COLLATE
){
5977 if( sqlite3_stricmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0 ) return 2;
5980 && pA
->op
!=TK_COLUMN
5981 && pA
->op
!=TK_AGG_COLUMN
5982 && strcmp(pA
->u
.zToken
,pB
->u
.zToken
)!=0
5987 if( (pA
->flags
& (EP_Distinct
|EP_Commuted
))
5988 != (pB
->flags
& (EP_Distinct
|EP_Commuted
)) ) return 2;
5989 if( ALWAYS((combinedFlags
& EP_TokenOnly
)==0) ){
5990 if( combinedFlags
& EP_xIsSelect
) return 2;
5991 if( (combinedFlags
& EP_FixedCol
)==0
5992 && sqlite3ExprCompare(pParse
, pA
->pLeft
, pB
->pLeft
, iTab
) ) return 2;
5993 if( sqlite3ExprCompare(pParse
, pA
->pRight
, pB
->pRight
, iTab
) ) return 2;
5994 if( sqlite3ExprListCompare(pA
->x
.pList
, pB
->x
.pList
, iTab
) ) return 2;
5995 if( pA
->op
!=TK_STRING
5996 && pA
->op
!=TK_TRUEFALSE
5997 && ALWAYS((combinedFlags
& EP_Reduced
)==0)
5999 if( pA
->iColumn
!=pB
->iColumn
) return 2;
6000 if( pA
->op2
!=pB
->op2
&& pA
->op
==TK_TRUTH
) return 2;
6001 if( pA
->op
!=TK_IN
&& pA
->iTable
!=pB
->iTable
&& pA
->iTable
!=iTab
){
6010 ** Compare two ExprList objects. Return 0 if they are identical, 1
6011 ** if they are certainly different, or 2 if it is not possible to
6012 ** determine if they are identical or not.
6014 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6015 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6017 ** This routine might return non-zero for equivalent ExprLists. The
6018 ** only consequence will be disabled optimizations. But this routine
6019 ** must never return 0 if the two ExprList objects are different, or
6020 ** a malfunction will result.
6022 ** Two NULL pointers are considered to be the same. But a NULL pointer
6023 ** always differs from a non-NULL pointer.
6025 int sqlite3ExprListCompare(const ExprList
*pA
, const ExprList
*pB
, int iTab
){
6027 if( pA
==0 && pB
==0 ) return 0;
6028 if( pA
==0 || pB
==0 ) return 1;
6029 if( pA
->nExpr
!=pB
->nExpr
) return 1;
6030 for(i
=0; i
<pA
->nExpr
; i
++){
6032 Expr
*pExprA
= pA
->a
[i
].pExpr
;
6033 Expr
*pExprB
= pB
->a
[i
].pExpr
;
6034 if( pA
->a
[i
].fg
.sortFlags
!=pB
->a
[i
].fg
.sortFlags
) return 1;
6035 if( (res
= sqlite3ExprCompare(0, pExprA
, pExprB
, iTab
)) ) return res
;
6041 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
6044 int sqlite3ExprCompareSkip(Expr
*pA
,Expr
*pB
, int iTab
){
6045 return sqlite3ExprCompare(0,
6046 sqlite3ExprSkipCollate(pA
),
6047 sqlite3ExprSkipCollate(pB
),
6052 ** Return non-zero if Expr p can only be true if pNN is not NULL.
6054 ** Or if seenNot is true, return non-zero if Expr p can only be
6055 ** non-NULL if pNN is not NULL
6057 static int exprImpliesNotNull(
6058 const Parse
*pParse
,/* Parsing context */
6059 const Expr
*p
, /* The expression to be checked */
6060 const Expr
*pNN
, /* The expression that is NOT NULL */
6061 int iTab
, /* Table being evaluated */
6062 int seenNot
/* Return true only if p can be any non-NULL value */
6066 if( sqlite3ExprCompare(pParse
, p
, pNN
, iTab
)==0 ){
6067 return pNN
->op
!=TK_NULL
;
6071 if( seenNot
&& ExprHasProperty(p
, EP_xIsSelect
) ) return 0;
6072 assert( ExprUseXSelect(p
) || (p
->x
.pList
!=0 && p
->x
.pList
->nExpr
>0) );
6073 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6077 assert( ExprUseXList(p
) );
6080 assert( pList
->nExpr
==2 );
6081 if( seenNot
) return 0;
6082 if( exprImpliesNotNull(pParse
, pList
->a
[0].pExpr
, pNN
, iTab
, 1)
6083 || exprImpliesNotNull(pParse
, pList
->a
[1].pExpr
, pNN
, iTab
, 1)
6087 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6102 /* no break */ deliberate_fall_through
6107 if( exprImpliesNotNull(pParse
, p
->pRight
, pNN
, iTab
, seenNot
) ) return 1;
6108 /* no break */ deliberate_fall_through
6114 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, seenNot
);
6117 if( seenNot
) return 0;
6118 if( p
->op2
!=TK_IS
) return 0;
6119 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6123 return exprImpliesNotNull(pParse
, p
->pLeft
, pNN
, iTab
, 1);
6130 ** Return true if we can prove the pE2 will always be true if pE1 is
6131 ** true. Return false if we cannot complete the proof or if pE2 might
6132 ** be false. Examples:
6134 ** pE1: x==5 pE2: x==5 Result: true
6135 ** pE1: x>0 pE2: x==5 Result: false
6136 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
6137 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
6138 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
6139 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
6140 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false
6142 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
6143 ** Expr.iTable<0 then assume a table number given by iTab.
6145 ** If pParse is not NULL, then the values of bound variables in pE1 are
6146 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
6147 ** modified to record which bound variables are referenced. If pParse
6148 ** is NULL, then false will be returned if pE1 contains any bound variables.
6150 ** When in doubt, return false. Returning true might give a performance
6151 ** improvement. Returning false might cause a performance reduction, but
6152 ** it will always give the correct answer and is hence always safe.
6154 int sqlite3ExprImpliesExpr(
6155 const Parse
*pParse
,
6160 if( sqlite3ExprCompare(pParse
, pE1
, pE2
, iTab
)==0 ){
6164 && (sqlite3ExprImpliesExpr(pParse
, pE1
, pE2
->pLeft
, iTab
)
6165 || sqlite3ExprImpliesExpr(pParse
, pE1
, pE2
->pRight
, iTab
) )
6169 if( pE2
->op
==TK_NOTNULL
6170 && exprImpliesNotNull(pParse
, pE1
, pE2
->pLeft
, iTab
, 0)
6177 /* This is a helper function to impliesNotNullRow(). In this routine,
6178 ** set pWalker->eCode to one only if *both* of the input expressions
6179 ** separately have the implies-not-null-row property.
6181 static void bothImplyNotNullRow(Walker
*pWalker
, Expr
*pE1
, Expr
*pE2
){
6182 if( pWalker
->eCode
==0 ){
6183 sqlite3WalkExpr(pWalker
, pE1
);
6184 if( pWalker
->eCode
){
6186 sqlite3WalkExpr(pWalker
, pE2
);
6192 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
6193 ** If the expression node requires that the table at pWalker->iCur
6194 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
6196 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
6197 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when
6198 ** evaluating terms in the ON clause of an inner join.
6200 ** This routine controls an optimization. False positives (setting
6201 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
6202 ** (never setting pWalker->eCode) is a harmless missed optimization.
6204 static int impliesNotNullRow(Walker
*pWalker
, Expr
*pExpr
){
6205 testcase( pExpr
->op
==TK_AGG_COLUMN
);
6206 testcase( pExpr
->op
==TK_AGG_FUNCTION
);
6207 if( ExprHasProperty(pExpr
, EP_OuterON
) ) return WRC_Prune
;
6208 if( ExprHasProperty(pExpr
, EP_InnerON
) && pWalker
->mWFlags
){
6209 /* If iCur is used in an inner-join ON clause to the left of a
6210 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
6211 ** But it is difficult to check for that condition precisely.
6212 ** To keep things simple, any use of iCur from any inner-join is
6213 ** ignored while attempting to simplify a RIGHT JOIN. */
6216 switch( pExpr
->op
){
6225 testcase( pExpr
->op
==TK_ISNOT
);
6226 testcase( pExpr
->op
==TK_ISNULL
);
6227 testcase( pExpr
->op
==TK_NOTNULL
);
6228 testcase( pExpr
->op
==TK_IS
);
6229 testcase( pExpr
->op
==TK_VECTOR
);
6230 testcase( pExpr
->op
==TK_FUNCTION
);
6231 testcase( pExpr
->op
==TK_TRUTH
);
6232 testcase( pExpr
->op
==TK_CASE
);
6236 if( pWalker
->u
.iCur
==pExpr
->iTable
){
6244 /* Both sides of an AND or OR must separately imply non-null-row.
6245 ** Consider these cases:
6248 ** If only one of x or y is non-null-row, then the overall expression
6249 ** can be true if the other arm is false (case 1) or true (case 2).
6251 testcase( pExpr
->op
==TK_OR
);
6252 testcase( pExpr
->op
==TK_AND
);
6253 bothImplyNotNullRow(pWalker
, pExpr
->pLeft
, pExpr
->pRight
);
6257 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
6258 ** both of which can be true. But apart from these cases, if
6259 ** the left-hand side of the IN is NULL then the IN itself will be
6261 if( ExprUseXList(pExpr
) && ALWAYS(pExpr
->x
.pList
->nExpr
>0) ){
6262 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
6267 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
6268 ** both y and z must be non-null row */
6269 assert( ExprUseXList(pExpr
) );
6270 assert( pExpr
->x
.pList
->nExpr
==2 );
6271 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
6272 bothImplyNotNullRow(pWalker
, pExpr
->x
.pList
->a
[0].pExpr
,
6273 pExpr
->x
.pList
->a
[1].pExpr
);
6276 /* Virtual tables are allowed to use constraints like x=NULL. So
6277 ** a term of the form x=y does not prove that y is not null if x
6278 ** is the column of a virtual table */
6285 Expr
*pLeft
= pExpr
->pLeft
;
6286 Expr
*pRight
= pExpr
->pRight
;
6287 testcase( pExpr
->op
==TK_EQ
);
6288 testcase( pExpr
->op
==TK_NE
);
6289 testcase( pExpr
->op
==TK_LT
);
6290 testcase( pExpr
->op
==TK_LE
);
6291 testcase( pExpr
->op
==TK_GT
);
6292 testcase( pExpr
->op
==TK_GE
);
6293 /* The y.pTab=0 assignment in wherecode.c always happens after the
6294 ** impliesNotNullRow() test */
6295 assert( pLeft
->op
!=TK_COLUMN
|| ExprUseYTab(pLeft
) );
6296 assert( pRight
->op
!=TK_COLUMN
|| ExprUseYTab(pRight
) );
6297 if( (pLeft
->op
==TK_COLUMN
6298 && ALWAYS(pLeft
->y
.pTab
!=0)
6299 && IsVirtual(pLeft
->y
.pTab
))
6300 || (pRight
->op
==TK_COLUMN
6301 && ALWAYS(pRight
->y
.pTab
!=0)
6302 && IsVirtual(pRight
->y
.pTab
))
6306 /* no break */ deliberate_fall_through
6309 return WRC_Continue
;
6314 ** Return true (non-zero) if expression p can only be true if at least
6315 ** one column of table iTab is non-null. In other words, return true
6316 ** if expression p will always be NULL or false if every column of iTab
6319 ** False negatives are acceptable. In other words, it is ok to return
6320 ** zero even if expression p will never be true of every column of iTab
6321 ** is NULL. A false negative is merely a missed optimization opportunity.
6323 ** False positives are not allowed, however. A false positive may result
6324 ** in an incorrect answer.
6326 ** Terms of p that are marked with EP_OuterON (and hence that come from
6327 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6329 ** This routine is used to check if a LEFT JOIN can be converted into
6330 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6331 ** clause requires that some column of the right table of the LEFT JOIN
6332 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6335 int sqlite3ExprImpliesNonNullRow(Expr
*p
, int iTab
, int isRJ
){
6337 p
= sqlite3ExprSkipCollateAndLikely(p
);
6338 if( p
==0 ) return 0;
6339 if( p
->op
==TK_NOTNULL
){
6342 while( p
->op
==TK_AND
){
6343 if( sqlite3ExprImpliesNonNullRow(p
->pLeft
, iTab
, isRJ
) ) return 1;
6347 w
.xExprCallback
= impliesNotNullRow
;
6348 w
.xSelectCallback
= 0;
6349 w
.xSelectCallback2
= 0;
6351 w
.mWFlags
= isRJ
!=0;
6353 sqlite3WalkExpr(&w
, p
);
6358 ** An instance of the following structure is used by the tree walker
6359 ** to determine if an expression can be evaluated by reference to the
6360 ** index only, without having to do a search for the corresponding
6361 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6362 ** is the cursor for the table.
6365 Index
*pIdx
; /* The index to be tested for coverage */
6366 int iCur
; /* Cursor number for the table corresponding to the index */
6370 ** Check to see if there are references to columns in table
6371 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6372 ** pWalker->u.pIdxCover->pIdx.
6374 static int exprIdxCover(Walker
*pWalker
, Expr
*pExpr
){
6375 if( pExpr
->op
==TK_COLUMN
6376 && pExpr
->iTable
==pWalker
->u
.pIdxCover
->iCur
6377 && sqlite3TableColumnToIndex(pWalker
->u
.pIdxCover
->pIdx
, pExpr
->iColumn
)<0
6382 return WRC_Continue
;
6386 ** Determine if an index pIdx on table with cursor iCur contains will
6387 ** the expression pExpr. Return true if the index does cover the
6388 ** expression and false if the pExpr expression references table columns
6389 ** that are not found in the index pIdx.
6391 ** An index covering an expression means that the expression can be
6392 ** evaluated using only the index and without having to lookup the
6393 ** corresponding table entry.
6395 int sqlite3ExprCoveredByIndex(
6396 Expr
*pExpr
, /* The index to be tested */
6397 int iCur
, /* The cursor number for the corresponding table */
6398 Index
*pIdx
/* The index that might be used for coverage */
6401 struct IdxCover xcov
;
6402 memset(&w
, 0, sizeof(w
));
6405 w
.xExprCallback
= exprIdxCover
;
6406 w
.u
.pIdxCover
= &xcov
;
6407 sqlite3WalkExpr(&w
, pExpr
);
6412 /* Structure used to pass information throughout the Walker in order to
6413 ** implement sqlite3ReferencesSrcList().
6416 sqlite3
*db
; /* Database connection used for sqlite3DbRealloc() */
6417 SrcList
*pRef
; /* Looking for references to these tables */
6418 i64 nExclude
; /* Number of tables to exclude from the search */
6419 int *aiExclude
; /* Cursor IDs for tables to exclude from the search */
6423 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6425 ** When entering a new subquery on the pExpr argument, add all FROM clause
6426 ** entries for that subquery to the exclude list.
6428 ** When leaving the subquery, remove those entries from the exclude list.
6430 static int selectRefEnter(Walker
*pWalker
, Select
*pSelect
){
6431 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6432 SrcList
*pSrc
= pSelect
->pSrc
;
6435 if( pSrc
->nSrc
==0 ) return WRC_Continue
;
6437 p
->nExclude
+= pSrc
->nSrc
;
6438 piNew
= sqlite3DbRealloc(p
->db
, p
->aiExclude
, p
->nExclude
*sizeof(int));
6443 p
->aiExclude
= piNew
;
6445 for(i
=0; i
<pSrc
->nSrc
; i
++, j
++){
6446 p
->aiExclude
[j
] = pSrc
->a
[i
].iCursor
;
6448 return WRC_Continue
;
6450 static void selectRefLeave(Walker
*pWalker
, Select
*pSelect
){
6451 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6452 SrcList
*pSrc
= pSelect
->pSrc
;
6454 assert( p
->nExclude
>=pSrc
->nSrc
);
6455 p
->nExclude
-= pSrc
->nSrc
;
6459 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6461 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6462 ** of the tables shown in RefSrcList.pRef.
6464 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6465 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6467 static int exprRefToSrcList(Walker
*pWalker
, Expr
*pExpr
){
6468 if( pExpr
->op
==TK_COLUMN
6469 || pExpr
->op
==TK_AGG_COLUMN
6472 struct RefSrcList
*p
= pWalker
->u
.pRefSrcList
;
6473 SrcList
*pSrc
= p
->pRef
;
6474 int nSrc
= pSrc
? pSrc
->nSrc
: 0;
6475 for(i
=0; i
<nSrc
; i
++){
6476 if( pExpr
->iTable
==pSrc
->a
[i
].iCursor
){
6477 pWalker
->eCode
|= 1;
6478 return WRC_Continue
;
6481 for(i
=0; i
<p
->nExclude
&& p
->aiExclude
[i
]!=pExpr
->iTable
; i
++){}
6482 if( i
>=p
->nExclude
){
6483 pWalker
->eCode
|= 2;
6486 return WRC_Continue
;
6490 ** Check to see if pExpr references any tables in pSrcList.
6491 ** Possible return values:
6493 ** 1 pExpr does references a table in pSrcList.
6495 ** 0 pExpr references some table that is not defined in either
6496 ** pSrcList or in subqueries of pExpr itself.
6498 ** -1 pExpr only references no tables at all, or it only
6499 ** references tables defined in subqueries of pExpr itself.
6501 ** As currently used, pExpr is always an aggregate function call. That
6502 ** fact is exploited for efficiency.
6504 int sqlite3ReferencesSrcList(Parse
*pParse
, Expr
*pExpr
, SrcList
*pSrcList
){
6506 struct RefSrcList x
;
6507 assert( pParse
->db
!=0 );
6508 memset(&w
, 0, sizeof(w
));
6509 memset(&x
, 0, sizeof(x
));
6510 w
.xExprCallback
= exprRefToSrcList
;
6511 w
.xSelectCallback
= selectRefEnter
;
6512 w
.xSelectCallback2
= selectRefLeave
;
6513 w
.u
.pRefSrcList
= &x
;
6516 assert( pExpr
->op
==TK_AGG_FUNCTION
);
6517 assert( ExprUseXList(pExpr
) );
6518 sqlite3WalkExprList(&w
, pExpr
->x
.pList
);
6520 assert( pExpr
->pLeft
->op
==TK_ORDER
);
6521 assert( ExprUseXList(pExpr
->pLeft
) );
6522 assert( pExpr
->pLeft
->x
.pList
!=0 );
6523 sqlite3WalkExprList(&w
, pExpr
->pLeft
->x
.pList
);
6525 #ifndef SQLITE_OMIT_WINDOWFUNC
6526 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
6527 sqlite3WalkExpr(&w
, pExpr
->y
.pWin
->pFilter
);
6530 if( x
.aiExclude
) sqlite3DbNNFreeNN(pParse
->db
, x
.aiExclude
);
6531 if( w
.eCode
& 0x01 ){
6533 }else if( w
.eCode
){
6541 ** This is a Walker expression node callback.
6543 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6544 ** object that is referenced does not refer directly to the Expr. If
6545 ** it does, make a copy. This is done because the pExpr argument is
6546 ** subject to change.
6548 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6549 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6551 static int agginfoPersistExprCb(Walker
*pWalker
, Expr
*pExpr
){
6552 if( ALWAYS(!ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
))
6553 && pExpr
->pAggInfo
!=0
6555 AggInfo
*pAggInfo
= pExpr
->pAggInfo
;
6556 int iAgg
= pExpr
->iAgg
;
6557 Parse
*pParse
= pWalker
->pParse
;
6558 sqlite3
*db
= pParse
->db
;
6560 if( pExpr
->op
!=TK_AGG_FUNCTION
){
6561 if( iAgg
<pAggInfo
->nColumn
6562 && pAggInfo
->aCol
[iAgg
].pCExpr
==pExpr
6564 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
6566 pAggInfo
->aCol
[iAgg
].pCExpr
= pExpr
;
6567 sqlite3ExprDeferredDelete(pParse
, pExpr
);
6571 assert( pExpr
->op
==TK_AGG_FUNCTION
);
6572 if( ALWAYS(iAgg
<pAggInfo
->nFunc
)
6573 && pAggInfo
->aFunc
[iAgg
].pFExpr
==pExpr
6575 pExpr
= sqlite3ExprDup(db
, pExpr
, 0);
6577 pAggInfo
->aFunc
[iAgg
].pFExpr
= pExpr
;
6578 sqlite3ExprDeferredDelete(pParse
, pExpr
);
6583 return WRC_Continue
;
6587 ** Initialize a Walker object so that will persist AggInfo entries referenced
6588 ** by the tree that is walked.
6590 void sqlite3AggInfoPersistWalkerInit(Walker
*pWalker
, Parse
*pParse
){
6591 memset(pWalker
, 0, sizeof(*pWalker
));
6592 pWalker
->pParse
= pParse
;
6593 pWalker
->xExprCallback
= agginfoPersistExprCb
;
6594 pWalker
->xSelectCallback
= sqlite3SelectWalkNoop
;
6598 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6599 ** the new element. Return a negative number if malloc fails.
6601 static int addAggInfoColumn(sqlite3
*db
, AggInfo
*pInfo
){
6603 pInfo
->aCol
= sqlite3ArrayAllocate(
6606 sizeof(pInfo
->aCol
[0]),
6614 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6615 ** the new element. Return a negative number if malloc fails.
6617 static int addAggInfoFunc(sqlite3
*db
, AggInfo
*pInfo
){
6619 pInfo
->aFunc
= sqlite3ArrayAllocate(
6622 sizeof(pInfo
->aFunc
[0]),
6630 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6631 ** Return the index in aCol[] of the entry that describes that column.
6633 ** If no prior entry is found, create a new one and return -1. The
6634 ** new column will have an index of pAggInfo->nColumn-1.
6636 static void findOrCreateAggInfoColumn(
6637 Parse
*pParse
, /* Parsing context */
6638 AggInfo
*pAggInfo
, /* The AggInfo object to search and/or modify */
6639 Expr
*pExpr
/* Expr describing the column to find or insert */
6641 struct AggInfo_col
*pCol
;
6644 assert( pAggInfo
->iFirstReg
==0 );
6645 pCol
= pAggInfo
->aCol
;
6646 for(k
=0; k
<pAggInfo
->nColumn
; k
++, pCol
++){
6647 if( pCol
->pCExpr
==pExpr
) return;
6648 if( pCol
->iTable
==pExpr
->iTable
6649 && pCol
->iColumn
==pExpr
->iColumn
6650 && pExpr
->op
!=TK_IF_NULL_ROW
6655 k
= addAggInfoColumn(pParse
->db
, pAggInfo
);
6658 assert( pParse
->db
->mallocFailed
);
6661 pCol
= &pAggInfo
->aCol
[k
];
6662 assert( ExprUseYTab(pExpr
) );
6663 pCol
->pTab
= pExpr
->y
.pTab
;
6664 pCol
->iTable
= pExpr
->iTable
;
6665 pCol
->iColumn
= pExpr
->iColumn
;
6666 pCol
->iSorterColumn
= -1;
6667 pCol
->pCExpr
= pExpr
;
6668 if( pAggInfo
->pGroupBy
&& pExpr
->op
!=TK_IF_NULL_ROW
){
6670 ExprList
*pGB
= pAggInfo
->pGroupBy
;
6671 struct ExprList_item
*pTerm
= pGB
->a
;
6673 for(j
=0; j
<n
; j
++, pTerm
++){
6674 Expr
*pE
= pTerm
->pExpr
;
6675 if( pE
->op
==TK_COLUMN
6676 && pE
->iTable
==pExpr
->iTable
6677 && pE
->iColumn
==pExpr
->iColumn
6679 pCol
->iSorterColumn
= j
;
6684 if( pCol
->iSorterColumn
<0 ){
6685 pCol
->iSorterColumn
= pAggInfo
->nSortingColumn
++;
6688 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
6689 assert( pExpr
->pAggInfo
==0 || pExpr
->pAggInfo
==pAggInfo
);
6690 pExpr
->pAggInfo
= pAggInfo
;
6691 if( pExpr
->op
==TK_COLUMN
){
6692 pExpr
->op
= TK_AGG_COLUMN
;
6694 pExpr
->iAgg
= (i16
)k
;
6698 ** This is the xExprCallback for a tree walker. It is used to
6699 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
6700 ** for additional information.
6702 static int analyzeAggregate(Walker
*pWalker
, Expr
*pExpr
){
6704 NameContext
*pNC
= pWalker
->u
.pNC
;
6705 Parse
*pParse
= pNC
->pParse
;
6706 SrcList
*pSrcList
= pNC
->pSrcList
;
6707 AggInfo
*pAggInfo
= pNC
->uNC
.pAggInfo
;
6709 assert( pNC
->ncFlags
& NC_UAggInfo
);
6710 assert( pAggInfo
->iFirstReg
==0 );
6711 switch( pExpr
->op
){
6715 assert( pParse
->iSelfTab
==0 );
6716 if( (pNC
->ncFlags
& NC_InAggFunc
)==0 ) break;
6717 if( pParse
->pIdxEpr
==0 ) break;
6718 for(pIEpr
=pParse
->pIdxEpr
; pIEpr
; pIEpr
=pIEpr
->pIENext
){
6719 int iDataCur
= pIEpr
->iDataCur
;
6720 if( iDataCur
<0 ) continue;
6721 if( sqlite3ExprCompare(0, pExpr
, pIEpr
->pExpr
, iDataCur
)==0 ) break;
6723 if( pIEpr
==0 ) break;
6724 if( NEVER(!ExprUseYTab(pExpr
)) ) break;
6725 for(i
=0; i
<pSrcList
->nSrc
; i
++){
6726 if( pSrcList
->a
[0].iCursor
==pIEpr
->iDataCur
) break;
6728 if( i
>=pSrcList
->nSrc
) break;
6729 if( NEVER(pExpr
->pAggInfo
!=0) ) break; /* Resolved by outer context */
6730 if( pParse
->nErr
){ return WRC_Abort
; }
6732 /* If we reach this point, it means that expression pExpr can be
6733 ** translated into a reference to an index column as described by
6736 memset(&tmp
, 0, sizeof(tmp
));
6737 tmp
.op
= TK_AGG_COLUMN
;
6738 tmp
.iTable
= pIEpr
->iIdxCur
;
6739 tmp
.iColumn
= pIEpr
->iIdxCol
;
6740 findOrCreateAggInfoColumn(pParse
, pAggInfo
, &tmp
);
6741 if( pParse
->nErr
){ return WRC_Abort
; }
6742 assert( pAggInfo
->aCol
!=0 );
6743 assert( tmp
.iAgg
<pAggInfo
->nColumn
);
6744 pAggInfo
->aCol
[tmp
.iAgg
].pCExpr
= pExpr
;
6745 pExpr
->pAggInfo
= pAggInfo
;
6746 pExpr
->iAgg
= tmp
.iAgg
;
6749 case TK_IF_NULL_ROW
:
6752 testcase( pExpr
->op
==TK_AGG_COLUMN
);
6753 testcase( pExpr
->op
==TK_COLUMN
);
6754 testcase( pExpr
->op
==TK_IF_NULL_ROW
);
6755 /* Check to see if the column is in one of the tables in the FROM
6756 ** clause of the aggregate query */
6757 if( ALWAYS(pSrcList
!=0) ){
6758 SrcItem
*pItem
= pSrcList
->a
;
6759 for(i
=0; i
<pSrcList
->nSrc
; i
++, pItem
++){
6760 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
6761 if( pExpr
->iTable
==pItem
->iCursor
){
6762 findOrCreateAggInfoColumn(pParse
, pAggInfo
, pExpr
);
6764 } /* endif pExpr->iTable==pItem->iCursor */
6765 } /* end loop over pSrcList */
6767 return WRC_Continue
;
6769 case TK_AGG_FUNCTION
: {
6770 if( (pNC
->ncFlags
& NC_InAggFunc
)==0
6771 && pWalker
->walkerDepth
==pExpr
->op2
6773 /* Check to see if pExpr is a duplicate of another aggregate
6774 ** function that is already in the pAggInfo structure
6776 struct AggInfo_func
*pItem
= pAggInfo
->aFunc
;
6777 for(i
=0; i
<pAggInfo
->nFunc
; i
++, pItem
++){
6778 if( pItem
->pFExpr
==pExpr
) break;
6779 if( sqlite3ExprCompare(0, pItem
->pFExpr
, pExpr
, -1)==0 ){
6783 if( i
>=pAggInfo
->nFunc
){
6784 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
6786 u8 enc
= ENC(pParse
->db
);
6787 i
= addAggInfoFunc(pParse
->db
, pAggInfo
);
6790 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
6791 pItem
= &pAggInfo
->aFunc
[i
];
6792 pItem
->pFExpr
= pExpr
;
6793 assert( ExprUseUToken(pExpr
) );
6794 nArg
= pExpr
->x
.pList
? pExpr
->x
.pList
->nExpr
: 0;
6795 pItem
->pFunc
= sqlite3FindFunction(pParse
->db
,
6796 pExpr
->u
.zToken
, nArg
, enc
, 0);
6797 assert( pItem
->bOBUnique
==0 );
6799 && (pItem
->pFunc
->funcFlags
& SQLITE_FUNC_NEEDCOLL
)==0
6801 /* The NEEDCOLL test above causes any ORDER BY clause on
6802 ** aggregate min() or max() to be ignored. */
6805 assert( pExpr
->pLeft
->op
==TK_ORDER
);
6806 assert( ExprUseXList(pExpr
->pLeft
) );
6807 pItem
->iOBTab
= pParse
->nTab
++;
6808 pOBList
= pExpr
->pLeft
->x
.pList
;
6809 assert( pOBList
->nExpr
>0 );
6810 assert( pItem
->bOBUnique
==0 );
6811 if( pOBList
->nExpr
==1
6813 && sqlite3ExprCompare(0,pOBList
->a
[0].pExpr
,
6814 pExpr
->x
.pList
->a
[0].pExpr
,0)==0
6816 pItem
->bOBPayload
= 0;
6817 pItem
->bOBUnique
= ExprHasProperty(pExpr
, EP_Distinct
);
6819 pItem
->bOBPayload
= 1;
6824 if( ExprHasProperty(pExpr
, EP_Distinct
) && !pItem
->bOBUnique
){
6825 pItem
->iDistinct
= pParse
->nTab
++;
6827 pItem
->iDistinct
= -1;
6831 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6833 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
6834 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
6835 pExpr
->iAgg
= (i16
)i
;
6836 pExpr
->pAggInfo
= pAggInfo
;
6839 return WRC_Continue
;
6843 return WRC_Continue
;
6847 ** Analyze the pExpr expression looking for aggregate functions and
6848 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6849 ** points to. Additional entries are made on the AggInfo object as
6852 ** This routine should only be called after the expression has been
6853 ** analyzed by sqlite3ResolveExprNames().
6855 void sqlite3ExprAnalyzeAggregates(NameContext
*pNC
, Expr
*pExpr
){
6857 w
.xExprCallback
= analyzeAggregate
;
6858 w
.xSelectCallback
= sqlite3WalkerDepthIncrease
;
6859 w
.xSelectCallback2
= sqlite3WalkerDepthDecrease
;
6863 assert( pNC
->pSrcList
!=0 );
6864 sqlite3WalkExpr(&w
, pExpr
);
6868 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
6869 ** expression list. Return the number of errors.
6871 ** If an error is found, the analysis is cut short.
6873 void sqlite3ExprAnalyzeAggList(NameContext
*pNC
, ExprList
*pList
){
6874 struct ExprList_item
*pItem
;
6877 for(pItem
=pList
->a
, i
=0; i
<pList
->nExpr
; i
++, pItem
++){
6878 sqlite3ExprAnalyzeAggregates(pNC
, pItem
->pExpr
);
6884 ** Allocate a single new register for use to hold some intermediate result.
6886 int sqlite3GetTempReg(Parse
*pParse
){
6887 if( pParse
->nTempReg
==0 ){
6888 return ++pParse
->nMem
;
6890 return pParse
->aTempReg
[--pParse
->nTempReg
];
6894 ** Deallocate a register, making available for reuse for some other
6897 void sqlite3ReleaseTempReg(Parse
*pParse
, int iReg
){
6899 sqlite3VdbeReleaseRegisters(pParse
, iReg
, 1, 0, 0);
6900 if( pParse
->nTempReg
<ArraySize(pParse
->aTempReg
) ){
6901 pParse
->aTempReg
[pParse
->nTempReg
++] = iReg
;
6907 ** Allocate or deallocate a block of nReg consecutive registers.
6909 int sqlite3GetTempRange(Parse
*pParse
, int nReg
){
6911 if( nReg
==1 ) return sqlite3GetTempReg(pParse
);
6912 i
= pParse
->iRangeReg
;
6913 n
= pParse
->nRangeReg
;
6915 pParse
->iRangeReg
+= nReg
;
6916 pParse
->nRangeReg
-= nReg
;
6919 pParse
->nMem
+= nReg
;
6923 void sqlite3ReleaseTempRange(Parse
*pParse
, int iReg
, int nReg
){
6925 sqlite3ReleaseTempReg(pParse
, iReg
);
6928 sqlite3VdbeReleaseRegisters(pParse
, iReg
, nReg
, 0, 0);
6929 if( nReg
>pParse
->nRangeReg
){
6930 pParse
->nRangeReg
= nReg
;
6931 pParse
->iRangeReg
= iReg
;
6936 ** Mark all temporary registers as being unavailable for reuse.
6938 ** Always invoke this procedure after coding a subroutine or co-routine
6939 ** that might be invoked from other parts of the code, to ensure that
6940 ** the sub/co-routine does not use registers in common with the code that
6941 ** invokes the sub/co-routine.
6943 void sqlite3ClearTempRegCache(Parse
*pParse
){
6944 pParse
->nTempReg
= 0;
6945 pParse
->nRangeReg
= 0;
6949 ** Make sure sufficient registers have been allocated so that
6950 ** iReg is a valid register number.
6952 void sqlite3TouchRegister(Parse
*pParse
, int iReg
){
6953 if( pParse
->nMem
<iReg
) pParse
->nMem
= iReg
;
6956 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
6958 ** Return the latest reusable register in the set of all registers.
6959 ** The value returned is no less than iMin. If any register iMin or
6960 ** greater is in permanent use, then return one more than that last
6961 ** permanent register.
6963 int sqlite3FirstAvailableRegister(Parse
*pParse
, int iMin
){
6964 const ExprList
*pList
= pParse
->pConstExpr
;
6967 for(i
=0; i
<pList
->nExpr
; i
++){
6968 if( pList
->a
[i
].u
.iConstExprReg
>=iMin
){
6969 iMin
= pList
->a
[i
].u
.iConstExprReg
+ 1;
6973 pParse
->nTempReg
= 0;
6974 pParse
->nRangeReg
= 0;
6977 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
6980 ** Validate that no temporary register falls within the range of
6981 ** iFirst..iLast, inclusive. This routine is only call from within assert()
6985 int sqlite3NoTempsInRange(Parse
*pParse
, int iFirst
, int iLast
){
6987 if( pParse
->nRangeReg
>0
6988 && pParse
->iRangeReg
+pParse
->nRangeReg
> iFirst
6989 && pParse
->iRangeReg
<= iLast
6993 for(i
=0; i
<pParse
->nTempReg
; i
++){
6994 if( pParse
->aTempReg
[i
]>=iFirst
&& pParse
->aTempReg
[i
]<=iLast
){
6998 if( pParse
->pConstExpr
){
6999 ExprList
*pList
= pParse
->pConstExpr
;
7000 for(i
=0; i
<pList
->nExpr
; i
++){
7001 int iReg
= pList
->a
[i
].u
.iConstExprReg
;
7002 if( iReg
==0 ) continue;
7003 if( iReg
>=iFirst
&& iReg
<=iLast
) return 0;
7008 #endif /* SQLITE_DEBUG */