fix typo in configure instructions
[sqlcipher.git] / src / expr.c
blobb64ea28bf5e953535e6d0880c76bd8760afcbaaa
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
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(Table *pTab, int iCol){
25 assert( iCol<pTab->nCol );
26 return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
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
38 ** have an affinity:
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){
46 int op;
47 while( ExprHasProperty(pExpr, EP_Skip) ){
48 assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );
49 pExpr = pExpr->pLeft;
50 assert( pExpr!=0 );
52 op = pExpr->op;
53 if( op==TK_SELECT ){
54 assert( pExpr->flags&EP_xIsSelect );
55 assert( pExpr->x.pSelect!=0 );
56 assert( pExpr->x.pSelect->pEList!=0 );
57 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
58 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
60 if( op==TK_REGISTER ) op = pExpr->op2;
61 #ifndef SQLITE_OMIT_CAST
62 if( op==TK_CAST ){
63 assert( !ExprHasProperty(pExpr, EP_IntValue) );
64 return sqlite3AffinityType(pExpr->u.zToken, 0);
66 #endif
67 if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
68 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
70 if( op==TK_SELECT_COLUMN ){
71 assert( pExpr->pLeft->flags&EP_xIsSelect );
72 return sqlite3ExprAffinity(
73 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
76 if( op==TK_VECTOR ){
77 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
79 return pExpr->affExpr;
83 ** Set the collating sequence for expression pExpr to be the collating
84 ** sequence named by pToken. Return a pointer to a new Expr node that
85 ** implements the COLLATE operator.
87 ** If a memory allocation error occurs, that fact is recorded in pParse->db
88 ** and the pExpr parameter is returned unchanged.
90 Expr *sqlite3ExprAddCollateToken(
91 Parse *pParse, /* Parsing context */
92 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
93 const Token *pCollName, /* Name of collating sequence */
94 int dequote /* True to dequote pCollName */
96 if( pCollName->n>0 ){
97 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
98 if( pNew ){
99 pNew->pLeft = pExpr;
100 pNew->flags |= EP_Collate|EP_Skip;
101 pExpr = pNew;
104 return pExpr;
106 Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
107 Token s;
108 assert( zC!=0 );
109 sqlite3TokenInit(&s, (char*)zC);
110 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
114 ** Skip over any TK_COLLATE operators.
116 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
117 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
118 assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );
119 pExpr = pExpr->pLeft;
121 return pExpr;
125 ** Skip over any TK_COLLATE operators and/or any unlikely()
126 ** or likelihood() or likely() functions at the root of an
127 ** expression.
129 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
130 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
131 if( ExprHasProperty(pExpr, EP_Unlikely) ){
132 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
133 assert( pExpr->x.pList->nExpr>0 );
134 assert( pExpr->op==TK_FUNCTION );
135 pExpr = pExpr->x.pList->a[0].pExpr;
136 }else{
137 assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );
138 pExpr = pExpr->pLeft;
141 return pExpr;
145 ** Return the collation sequence for the expression pExpr. If
146 ** there is no defined collating sequence, return NULL.
148 ** See also: sqlite3ExprNNCollSeq()
150 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
151 ** default collation if pExpr has no defined collation.
153 ** The collating sequence might be determined by a COLLATE operator
154 ** or by the presence of a column with a defined collating sequence.
155 ** COLLATE operators take first precedence. Left operands take
156 ** precedence over right operands.
158 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
159 sqlite3 *db = pParse->db;
160 CollSeq *pColl = 0;
161 const Expr *p = pExpr;
162 while( p ){
163 int op = p->op;
164 if( op==TK_REGISTER ) op = p->op2;
165 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
166 && p->y.pTab!=0
168 /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
169 ** a TK_COLUMN but was previously evaluated and cached in a register */
170 int j = p->iColumn;
171 if( j>=0 ){
172 const char *zColl = p->y.pTab->aCol[j].zColl;
173 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
175 break;
177 if( op==TK_CAST || op==TK_UPLUS ){
178 p = p->pLeft;
179 continue;
181 if( op==TK_VECTOR ){
182 p = p->x.pList->a[0].pExpr;
183 continue;
185 if( op==TK_COLLATE ){
186 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
187 break;
189 if( p->flags & EP_Collate ){
190 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
191 p = p->pLeft;
192 }else{
193 Expr *pNext = p->pRight;
194 /* The Expr.x union is never used at the same time as Expr.pRight */
195 assert( p->x.pList==0 || p->pRight==0 );
196 if( p->x.pList!=0
197 && !db->mallocFailed
198 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
200 int i;
201 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
202 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
203 pNext = p->x.pList->a[i].pExpr;
204 break;
208 p = pNext;
210 }else{
211 break;
214 if( sqlite3CheckCollSeq(pParse, pColl) ){
215 pColl = 0;
217 return pColl;
221 ** Return the collation sequence for the expression pExpr. If
222 ** there is no defined collating sequence, return a pointer to the
223 ** defautl collation sequence.
225 ** See also: sqlite3ExprCollSeq()
227 ** The sqlite3ExprCollSeq() routine works the same except that it
228 ** returns NULL if there is no defined collation.
230 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
231 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
232 if( p==0 ) p = pParse->db->pDfltColl;
233 assert( p!=0 );
234 return p;
238 ** Return TRUE if the two expressions have equivalent collating sequences.
240 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
241 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
242 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
243 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
247 ** pExpr is an operand of a comparison operator. aff2 is the
248 ** type affinity of the other operand. This routine returns the
249 ** type affinity that should be used for the comparison operator.
251 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
252 char aff1 = sqlite3ExprAffinity(pExpr);
253 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
254 /* Both sides of the comparison are columns. If one has numeric
255 ** affinity, use that. Otherwise use no affinity.
257 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
258 return SQLITE_AFF_NUMERIC;
259 }else{
260 return SQLITE_AFF_BLOB;
262 }else{
263 /* One side is a column, the other is not. Use the columns affinity. */
264 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
265 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
270 ** pExpr is a comparison operator. Return the type affinity that should
271 ** be applied to both operands prior to doing the comparison.
273 static char comparisonAffinity(const Expr *pExpr){
274 char aff;
275 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
276 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
277 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
278 assert( pExpr->pLeft );
279 aff = sqlite3ExprAffinity(pExpr->pLeft);
280 if( pExpr->pRight ){
281 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
282 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
283 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
284 }else if( aff==0 ){
285 aff = SQLITE_AFF_BLOB;
287 return aff;
291 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
292 ** idx_affinity is the affinity of an indexed column. Return true
293 ** if the index with affinity idx_affinity may be used to implement
294 ** the comparison in pExpr.
296 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
297 char aff = comparisonAffinity(pExpr);
298 if( aff<SQLITE_AFF_TEXT ){
299 return 1;
301 if( aff==SQLITE_AFF_TEXT ){
302 return idx_affinity==SQLITE_AFF_TEXT;
304 return sqlite3IsNumericAffinity(idx_affinity);
308 ** Return the P5 value that should be used for a binary comparison
309 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
311 static u8 binaryCompareP5(
312 const Expr *pExpr1, /* Left operand */
313 const Expr *pExpr2, /* Right operand */
314 int jumpIfNull /* Extra flags added to P5 */
316 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
317 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
318 return aff;
322 ** Return a pointer to the collation sequence that should be used by
323 ** a binary comparison operator comparing pLeft and pRight.
325 ** If the left hand expression has a collating sequence type, then it is
326 ** used. Otherwise the collation sequence for the right hand expression
327 ** is used, or the default (BINARY) if neither expression has a collating
328 ** type.
330 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
331 ** it is not considered.
333 CollSeq *sqlite3BinaryCompareCollSeq(
334 Parse *pParse,
335 const Expr *pLeft,
336 const Expr *pRight
338 CollSeq *pColl;
339 assert( pLeft );
340 if( pLeft->flags & EP_Collate ){
341 pColl = sqlite3ExprCollSeq(pParse, pLeft);
342 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
343 pColl = sqlite3ExprCollSeq(pParse, pRight);
344 }else{
345 pColl = sqlite3ExprCollSeq(pParse, pLeft);
346 if( !pColl ){
347 pColl = sqlite3ExprCollSeq(pParse, pRight);
350 return pColl;
353 /* Expresssion p is a comparison operator. Return a collation sequence
354 ** appropriate for the comparison operator.
356 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
357 ** However, if the OP_Commuted flag is set, then the order of the operands
358 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
359 ** correct collating sequence is found.
361 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
362 if( ExprHasProperty(p, EP_Commuted) ){
363 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
364 }else{
365 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
370 ** Generate code for a comparison operator.
372 static int codeCompare(
373 Parse *pParse, /* The parsing (and code generating) context */
374 Expr *pLeft, /* The left operand */
375 Expr *pRight, /* The right operand */
376 int opcode, /* The comparison opcode */
377 int in1, int in2, /* Register holding operands */
378 int dest, /* Jump here if true. */
379 int jumpIfNull, /* If true, jump if either operand is NULL */
380 int isCommuted /* The comparison has been commuted */
382 int p5;
383 int addr;
384 CollSeq *p4;
386 if( pParse->nErr ) return 0;
387 if( isCommuted ){
388 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
389 }else{
390 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
392 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
393 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
394 (void*)p4, P4_COLLSEQ);
395 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
396 return addr;
400 ** Return true if expression pExpr is a vector, or false otherwise.
402 ** A vector is defined as any expression that results in two or more
403 ** columns of result. Every TK_VECTOR node is an vector because the
404 ** parser will not generate a TK_VECTOR with fewer than two entries.
405 ** But a TK_SELECT might be either a vector or a scalar. It is only
406 ** considered a vector if it has two or more result columns.
408 int sqlite3ExprIsVector(Expr *pExpr){
409 return sqlite3ExprVectorSize(pExpr)>1;
413 ** If the expression passed as the only argument is of type TK_VECTOR
414 ** return the number of expressions in the vector. Or, if the expression
415 ** is a sub-select, return the number of columns in the sub-select. For
416 ** any other type of expression, return 1.
418 int sqlite3ExprVectorSize(Expr *pExpr){
419 u8 op = pExpr->op;
420 if( op==TK_REGISTER ) op = pExpr->op2;
421 if( op==TK_VECTOR ){
422 return pExpr->x.pList->nExpr;
423 }else if( op==TK_SELECT ){
424 return pExpr->x.pSelect->pEList->nExpr;
425 }else{
426 return 1;
431 ** Return a pointer to a subexpression of pVector that is the i-th
432 ** column of the vector (numbered starting with 0). The caller must
433 ** ensure that i is within range.
435 ** If pVector is really a scalar (and "scalar" here includes subqueries
436 ** that return a single column!) then return pVector unmodified.
438 ** pVector retains ownership of the returned subexpression.
440 ** If the vector is a (SELECT ...) then the expression returned is
441 ** just the expression for the i-th term of the result set, and may
442 ** not be ready for evaluation because the table cursor has not yet
443 ** been positioned.
445 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
446 assert( i<sqlite3ExprVectorSize(pVector) );
447 if( sqlite3ExprIsVector(pVector) ){
448 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
449 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
450 return pVector->x.pSelect->pEList->a[i].pExpr;
451 }else{
452 return pVector->x.pList->a[i].pExpr;
455 return pVector;
459 ** Compute and return a new Expr object which when passed to
460 ** sqlite3ExprCode() will generate all necessary code to compute
461 ** the iField-th column of the vector expression pVector.
463 ** It is ok for pVector to be a scalar (as long as iField==0).
464 ** In that case, this routine works like sqlite3ExprDup().
466 ** The caller owns the returned Expr object and is responsible for
467 ** ensuring that the returned value eventually gets freed.
469 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
470 ** then the returned object will reference pVector and so pVector must remain
471 ** valid for the life of the returned object. If pVector is a TK_VECTOR
472 ** or a scalar expression, then it can be deleted as soon as this routine
473 ** returns.
475 ** A trick to cause a TK_SELECT pVector to be deleted together with
476 ** the returned Expr object is to attach the pVector to the pRight field
477 ** of the returned TK_SELECT_COLUMN Expr object.
479 Expr *sqlite3ExprForVectorField(
480 Parse *pParse, /* Parsing context */
481 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
482 int iField /* Which column of the vector to return */
484 Expr *pRet;
485 if( pVector->op==TK_SELECT ){
486 assert( pVector->flags & EP_xIsSelect );
487 /* The TK_SELECT_COLUMN Expr node:
489 ** pLeft: pVector containing TK_SELECT. Not deleted.
490 ** pRight: not used. But recursively deleted.
491 ** iColumn: Index of a column in pVector
492 ** iTable: 0 or the number of columns on the LHS of an assignment
493 ** pLeft->iTable: First in an array of register holding result, or 0
494 ** if the result is not yet computed.
496 ** sqlite3ExprDelete() specifically skips the recursive delete of
497 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
498 ** can be attached to pRight to cause this node to take ownership of
499 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
500 ** with the same pLeft pointer to the pVector, but only one of them
501 ** will own the pVector.
503 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
504 if( pRet ){
505 pRet->iColumn = iField;
506 pRet->pLeft = pVector;
508 assert( pRet==0 || pRet->iTable==0 );
509 }else{
510 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
511 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
512 sqlite3RenameTokenRemap(pParse, pRet, pVector);
514 return pRet;
518 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
519 ** it. Return the register in which the result is stored (or, if the
520 ** sub-select returns more than one column, the first in an array
521 ** of registers in which the result is stored).
523 ** If pExpr is not a TK_SELECT expression, return 0.
525 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
526 int reg = 0;
527 #ifndef SQLITE_OMIT_SUBQUERY
528 if( pExpr->op==TK_SELECT ){
529 reg = sqlite3CodeSubselect(pParse, pExpr);
531 #endif
532 return reg;
536 ** Argument pVector points to a vector expression - either a TK_VECTOR
537 ** or TK_SELECT that returns more than one column. This function returns
538 ** the register number of a register that contains the value of
539 ** element iField of the vector.
541 ** If pVector is a TK_SELECT expression, then code for it must have
542 ** already been generated using the exprCodeSubselect() routine. In this
543 ** case parameter regSelect should be the first in an array of registers
544 ** containing the results of the sub-select.
546 ** If pVector is of type TK_VECTOR, then code for the requested field
547 ** is generated. In this case (*pRegFree) may be set to the number of
548 ** a temporary register to be freed by the caller before returning.
550 ** Before returning, output parameter (*ppExpr) is set to point to the
551 ** Expr object corresponding to element iElem of the vector.
553 static int exprVectorRegister(
554 Parse *pParse, /* Parse context */
555 Expr *pVector, /* Vector to extract element from */
556 int iField, /* Field to extract from pVector */
557 int regSelect, /* First in array of registers */
558 Expr **ppExpr, /* OUT: Expression element */
559 int *pRegFree /* OUT: Temp register to free */
561 u8 op = pVector->op;
562 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
563 if( op==TK_REGISTER ){
564 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
565 return pVector->iTable+iField;
567 if( op==TK_SELECT ){
568 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
569 return regSelect+iField;
571 *ppExpr = pVector->x.pList->a[iField].pExpr;
572 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
576 ** Expression pExpr is a comparison between two vector values. Compute
577 ** the result of the comparison (1, 0, or NULL) and write that
578 ** result into register dest.
580 ** The caller must satisfy the following preconditions:
582 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
583 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
584 ** otherwise: op==pExpr->op and p5==0
586 static void codeVectorCompare(
587 Parse *pParse, /* Code generator context */
588 Expr *pExpr, /* The comparison operation */
589 int dest, /* Write results into this register */
590 u8 op, /* Comparison operator */
591 u8 p5 /* SQLITE_NULLEQ or zero */
593 Vdbe *v = pParse->pVdbe;
594 Expr *pLeft = pExpr->pLeft;
595 Expr *pRight = pExpr->pRight;
596 int nLeft = sqlite3ExprVectorSize(pLeft);
597 int i;
598 int regLeft = 0;
599 int regRight = 0;
600 u8 opx = op;
601 int addrDone = sqlite3VdbeMakeLabel(pParse);
602 int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
604 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
605 if( pParse->nErr ) return;
606 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
607 sqlite3ErrorMsg(pParse, "row value misused");
608 return;
610 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
611 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
612 || pExpr->op==TK_LT || pExpr->op==TK_GT
613 || pExpr->op==TK_LE || pExpr->op==TK_GE
615 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
616 || (pExpr->op==TK_ISNOT && op==TK_NE) );
617 assert( p5==0 || pExpr->op!=op );
618 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
620 p5 |= SQLITE_STOREP2;
621 if( opx==TK_LE ) opx = TK_LT;
622 if( opx==TK_GE ) opx = TK_GT;
624 regLeft = exprCodeSubselect(pParse, pLeft);
625 regRight = exprCodeSubselect(pParse, pRight);
627 for(i=0; 1 /*Loop exits by "break"*/; i++){
628 int regFree1 = 0, regFree2 = 0;
629 Expr *pL, *pR;
630 int r1, r2;
631 assert( i>=0 && i<nLeft );
632 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
633 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
634 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
635 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
636 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
637 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
638 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
639 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
640 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
641 sqlite3ReleaseTempReg(pParse, regFree1);
642 sqlite3ReleaseTempReg(pParse, regFree2);
643 if( i==nLeft-1 ){
644 break;
646 if( opx==TK_EQ ){
647 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
648 p5 |= SQLITE_KEEPNULL;
649 }else if( opx==TK_NE ){
650 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
651 p5 |= SQLITE_KEEPNULL;
652 }else{
653 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
654 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
655 VdbeCoverageIf(v, op==TK_LT);
656 VdbeCoverageIf(v, op==TK_GT);
657 VdbeCoverageIf(v, op==TK_LE);
658 VdbeCoverageIf(v, op==TK_GE);
659 if( i==nLeft-2 ) opx = op;
662 sqlite3VdbeResolveLabel(v, addrDone);
665 #if SQLITE_MAX_EXPR_DEPTH>0
667 ** Check that argument nHeight is less than or equal to the maximum
668 ** expression depth allowed. If it is not, leave an error message in
669 ** pParse.
671 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
672 int rc = SQLITE_OK;
673 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
674 if( nHeight>mxHeight ){
675 sqlite3ErrorMsg(pParse,
676 "Expression tree is too large (maximum depth %d)", mxHeight
678 rc = SQLITE_ERROR;
680 return rc;
683 /* The following three functions, heightOfExpr(), heightOfExprList()
684 ** and heightOfSelect(), are used to determine the maximum height
685 ** of any expression tree referenced by the structure passed as the
686 ** first argument.
688 ** If this maximum height is greater than the current value pointed
689 ** to by pnHeight, the second parameter, then set *pnHeight to that
690 ** value.
692 static void heightOfExpr(Expr *p, int *pnHeight){
693 if( p ){
694 if( p->nHeight>*pnHeight ){
695 *pnHeight = p->nHeight;
699 static void heightOfExprList(ExprList *p, int *pnHeight){
700 if( p ){
701 int i;
702 for(i=0; i<p->nExpr; i++){
703 heightOfExpr(p->a[i].pExpr, pnHeight);
707 static void heightOfSelect(Select *pSelect, int *pnHeight){
708 Select *p;
709 for(p=pSelect; p; p=p->pPrior){
710 heightOfExpr(p->pWhere, pnHeight);
711 heightOfExpr(p->pHaving, pnHeight);
712 heightOfExpr(p->pLimit, pnHeight);
713 heightOfExprList(p->pEList, pnHeight);
714 heightOfExprList(p->pGroupBy, pnHeight);
715 heightOfExprList(p->pOrderBy, pnHeight);
720 ** Set the Expr.nHeight variable in the structure passed as an
721 ** argument. An expression with no children, Expr.pList or
722 ** Expr.pSelect member has a height of 1. Any other expression
723 ** has a height equal to the maximum height of any other
724 ** referenced Expr plus one.
726 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
727 ** if appropriate.
729 static void exprSetHeight(Expr *p){
730 int nHeight = 0;
731 heightOfExpr(p->pLeft, &nHeight);
732 heightOfExpr(p->pRight, &nHeight);
733 if( ExprHasProperty(p, EP_xIsSelect) ){
734 heightOfSelect(p->x.pSelect, &nHeight);
735 }else if( p->x.pList ){
736 heightOfExprList(p->x.pList, &nHeight);
737 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
739 p->nHeight = nHeight + 1;
743 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
744 ** the height is greater than the maximum allowed expression depth,
745 ** leave an error in pParse.
747 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
748 ** Expr.flags.
750 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
751 if( pParse->nErr ) return;
752 exprSetHeight(p);
753 sqlite3ExprCheckHeight(pParse, p->nHeight);
757 ** Return the maximum height of any expression tree referenced
758 ** by the select statement passed as an argument.
760 int sqlite3SelectExprHeight(Select *p){
761 int nHeight = 0;
762 heightOfSelect(p, &nHeight);
763 return nHeight;
765 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
767 ** Propagate all EP_Propagate flags from the Expr.x.pList into
768 ** Expr.flags.
770 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
771 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
772 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
775 #define exprSetHeight(y)
776 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
779 ** This routine is the core allocator for Expr nodes.
781 ** Construct a new expression node and return a pointer to it. Memory
782 ** for this node and for the pToken argument is a single allocation
783 ** obtained from sqlite3DbMalloc(). The calling function
784 ** is responsible for making sure the node eventually gets freed.
786 ** If dequote is true, then the token (if it exists) is dequoted.
787 ** If dequote is false, no dequoting is performed. The deQuote
788 ** parameter is ignored if pToken is NULL or if the token does not
789 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
790 ** then the EP_DblQuoted flag is set on the expression node.
792 ** Special case: If op==TK_INTEGER and pToken points to a string that
793 ** can be translated into a 32-bit integer, then the token is not
794 ** stored in u.zToken. Instead, the integer values is written
795 ** into u.iValue and the EP_IntValue flag is set. No extra storage
796 ** is allocated to hold the integer text and the dequote flag is ignored.
798 Expr *sqlite3ExprAlloc(
799 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
800 int op, /* Expression opcode */
801 const Token *pToken, /* Token argument. Might be NULL */
802 int dequote /* True to dequote */
804 Expr *pNew;
805 int nExtra = 0;
806 int iValue = 0;
808 assert( db!=0 );
809 if( pToken ){
810 if( op!=TK_INTEGER || pToken->z==0
811 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
812 nExtra = pToken->n+1;
813 assert( iValue>=0 );
816 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
817 if( pNew ){
818 memset(pNew, 0, sizeof(Expr));
819 pNew->op = (u8)op;
820 pNew->iAgg = -1;
821 if( pToken ){
822 if( nExtra==0 ){
823 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
824 pNew->u.iValue = iValue;
825 }else{
826 pNew->u.zToken = (char*)&pNew[1];
827 assert( pToken->z!=0 || pToken->n==0 );
828 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
829 pNew->u.zToken[pToken->n] = 0;
830 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
831 sqlite3DequoteExpr(pNew);
835 #if SQLITE_MAX_EXPR_DEPTH>0
836 pNew->nHeight = 1;
837 #endif
839 return pNew;
843 ** Allocate a new expression node from a zero-terminated token that has
844 ** already been dequoted.
846 Expr *sqlite3Expr(
847 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
848 int op, /* Expression opcode */
849 const char *zToken /* Token argument. Might be NULL */
851 Token x;
852 x.z = zToken;
853 x.n = sqlite3Strlen30(zToken);
854 return sqlite3ExprAlloc(db, op, &x, 0);
858 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
860 ** If pRoot==NULL that means that a memory allocation error has occurred.
861 ** In that case, delete the subtrees pLeft and pRight.
863 void sqlite3ExprAttachSubtrees(
864 sqlite3 *db,
865 Expr *pRoot,
866 Expr *pLeft,
867 Expr *pRight
869 if( pRoot==0 ){
870 assert( db->mallocFailed );
871 sqlite3ExprDelete(db, pLeft);
872 sqlite3ExprDelete(db, pRight);
873 }else{
874 if( pRight ){
875 pRoot->pRight = pRight;
876 pRoot->flags |= EP_Propagate & pRight->flags;
878 if( pLeft ){
879 pRoot->pLeft = pLeft;
880 pRoot->flags |= EP_Propagate & pLeft->flags;
882 exprSetHeight(pRoot);
887 ** Allocate an Expr node which joins as many as two subtrees.
889 ** One or both of the subtrees can be NULL. Return a pointer to the new
890 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
891 ** free the subtrees and return NULL.
893 Expr *sqlite3PExpr(
894 Parse *pParse, /* Parsing context */
895 int op, /* Expression opcode */
896 Expr *pLeft, /* Left operand */
897 Expr *pRight /* Right operand */
899 Expr *p;
900 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
901 if( p ){
902 memset(p, 0, sizeof(Expr));
903 p->op = op & 0xff;
904 p->iAgg = -1;
905 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
906 sqlite3ExprCheckHeight(pParse, p->nHeight);
907 }else{
908 sqlite3ExprDelete(pParse->db, pLeft);
909 sqlite3ExprDelete(pParse->db, pRight);
911 return p;
915 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
916 ** do a memory allocation failure) then delete the pSelect object.
918 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
919 if( pExpr ){
920 pExpr->x.pSelect = pSelect;
921 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
922 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
923 }else{
924 assert( pParse->db->mallocFailed );
925 sqlite3SelectDelete(pParse->db, pSelect);
931 ** Join two expressions using an AND operator. If either expression is
932 ** NULL, then just return the other expression.
934 ** If one side or the other of the AND is known to be false, then instead
935 ** of returning an AND expression, just return a constant expression with
936 ** a value of false.
938 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
939 sqlite3 *db = pParse->db;
940 if( pLeft==0 ){
941 return pRight;
942 }else if( pRight==0 ){
943 return pLeft;
944 }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight))
945 && !IN_RENAME_OBJECT
947 sqlite3ExprDelete(db, pLeft);
948 sqlite3ExprDelete(db, pRight);
949 return sqlite3Expr(db, TK_INTEGER, "0");
950 }else{
951 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
956 ** Construct a new expression node for a function with multiple
957 ** arguments.
959 Expr *sqlite3ExprFunction(
960 Parse *pParse, /* Parsing context */
961 ExprList *pList, /* Argument list */
962 Token *pToken, /* Name of the function */
963 int eDistinct /* SF_Distinct or SF_ALL or 0 */
965 Expr *pNew;
966 sqlite3 *db = pParse->db;
967 assert( pToken );
968 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
969 if( pNew==0 ){
970 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
971 return 0;
973 if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
974 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
976 pNew->x.pList = pList;
977 ExprSetProperty(pNew, EP_HasFunc);
978 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
979 sqlite3ExprSetHeightAndFlags(pParse, pNew);
980 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
981 return pNew;
985 ** Check to see if a function is usable according to current access
986 ** rules:
988 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
990 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
991 ** top-level SQL
993 ** If the function is not usable, create an error.
995 void sqlite3ExprFunctionUsable(
996 Parse *pParse, /* Parsing and code generating context */
997 Expr *pExpr, /* The function invocation */
998 FuncDef *pDef /* The function being invoked */
1000 assert( !IN_RENAME_OBJECT );
1001 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
1002 if( ExprHasProperty(pExpr, EP_FromDDL) ){
1003 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
1004 || (pParse->db->flags & SQLITE_TrustedSchema)==0
1006 /* Functions prohibited in triggers and views if:
1007 ** (1) tagged with SQLITE_DIRECTONLY
1008 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1009 ** is tagged with SQLITE_FUNC_UNSAFE) and
1010 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1011 ** that the schema is possibly tainted).
1013 sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName);
1019 ** Assign a variable number to an expression that encodes a wildcard
1020 ** in the original SQL statement.
1022 ** Wildcards consisting of a single "?" are assigned the next sequential
1023 ** variable number.
1025 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1026 ** sure "nnn" is not too big to avoid a denial of service attack when
1027 ** the SQL statement comes from an external source.
1029 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1030 ** as the previous instance of the same wildcard. Or if this is the first
1031 ** instance of the wildcard, the next sequential variable number is
1032 ** assigned.
1034 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
1035 sqlite3 *db = pParse->db;
1036 const char *z;
1037 ynVar x;
1039 if( pExpr==0 ) return;
1040 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
1041 z = pExpr->u.zToken;
1042 assert( z!=0 );
1043 assert( z[0]!=0 );
1044 assert( n==(u32)sqlite3Strlen30(z) );
1045 if( z[1]==0 ){
1046 /* Wildcard of the form "?". Assign the next variable number */
1047 assert( z[0]=='?' );
1048 x = (ynVar)(++pParse->nVar);
1049 }else{
1050 int doAdd = 0;
1051 if( z[0]=='?' ){
1052 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1053 ** use it as the variable number */
1054 i64 i;
1055 int bOk;
1056 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1057 i = z[1]-'0'; /* The common case of ?N for a single digit N */
1058 bOk = 1;
1059 }else{
1060 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1062 testcase( i==0 );
1063 testcase( i==1 );
1064 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1065 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1066 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1067 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1068 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1069 return;
1071 x = (ynVar)i;
1072 if( x>pParse->nVar ){
1073 pParse->nVar = (int)x;
1074 doAdd = 1;
1075 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1076 doAdd = 1;
1078 }else{
1079 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1080 ** number as the prior appearance of the same name, or if the name
1081 ** has never appeared before, reuse the same variable number
1083 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1084 if( x==0 ){
1085 x = (ynVar)(++pParse->nVar);
1086 doAdd = 1;
1089 if( doAdd ){
1090 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1093 pExpr->iColumn = x;
1094 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1095 sqlite3ErrorMsg(pParse, "too many SQL variables");
1100 ** Recursively delete an expression tree.
1102 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1103 assert( p!=0 );
1104 /* Sanity check: Assert that the IntValue is non-negative if it exists */
1105 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
1107 assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
1108 assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
1109 || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
1110 #ifdef SQLITE_DEBUG
1111 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1112 assert( p->pLeft==0 );
1113 assert( p->pRight==0 );
1114 assert( p->x.pSelect==0 );
1116 #endif
1117 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1118 /* The Expr.x union is never used at the same time as Expr.pRight */
1119 assert( p->x.pList==0 || p->pRight==0 );
1120 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1121 if( p->pRight ){
1122 assert( !ExprHasProperty(p, EP_WinFunc) );
1123 sqlite3ExprDeleteNN(db, p->pRight);
1124 }else if( ExprHasProperty(p, EP_xIsSelect) ){
1125 assert( !ExprHasProperty(p, EP_WinFunc) );
1126 sqlite3SelectDelete(db, p->x.pSelect);
1127 }else{
1128 sqlite3ExprListDelete(db, p->x.pList);
1129 #ifndef SQLITE_OMIT_WINDOWFUNC
1130 if( ExprHasProperty(p, EP_WinFunc) ){
1131 sqlite3WindowDelete(db, p->y.pWin);
1133 #endif
1136 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
1137 if( !ExprHasProperty(p, EP_Static) ){
1138 sqlite3DbFreeNN(db, p);
1141 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1142 if( p ) sqlite3ExprDeleteNN(db, p);
1145 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1146 ** expression.
1148 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
1149 if( p ){
1150 if( IN_RENAME_OBJECT ){
1151 sqlite3RenameExprUnmap(pParse, p);
1153 sqlite3ExprDeleteNN(pParse->db, p);
1158 ** Return the number of bytes allocated for the expression structure
1159 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1160 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1162 static int exprStructSize(Expr *p){
1163 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1164 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1165 return EXPR_FULLSIZE;
1169 ** The dupedExpr*Size() routines each return the number of bytes required
1170 ** to store a copy of an expression or expression tree. They differ in
1171 ** how much of the tree is measured.
1173 ** dupedExprStructSize() Size of only the Expr structure
1174 ** dupedExprNodeSize() Size of Expr + space for token
1175 ** dupedExprSize() Expr + token + subtree components
1177 ***************************************************************************
1179 ** The dupedExprStructSize() function returns two values OR-ed together:
1180 ** (1) the space required for a copy of the Expr structure only and
1181 ** (2) the EP_xxx flags that indicate what the structure size should be.
1182 ** The return values is always one of:
1184 ** EXPR_FULLSIZE
1185 ** EXPR_REDUCEDSIZE | EP_Reduced
1186 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1188 ** The size of the structure can be found by masking the return value
1189 ** of this routine with 0xfff. The flags can be found by masking the
1190 ** return value with EP_Reduced|EP_TokenOnly.
1192 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1193 ** (unreduced) Expr objects as they or originally constructed by the parser.
1194 ** During expression analysis, extra information is computed and moved into
1195 ** later parts of the Expr object and that extra information might get chopped
1196 ** off if the expression is reduced. Note also that it does not work to
1197 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1198 ** to reduce a pristine expression tree from the parser. The implementation
1199 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1200 ** to enforce this constraint.
1202 static int dupedExprStructSize(Expr *p, int flags){
1203 int nSize;
1204 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1205 assert( EXPR_FULLSIZE<=0xfff );
1206 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1207 if( 0==flags || p->op==TK_SELECT_COLUMN
1208 #ifndef SQLITE_OMIT_WINDOWFUNC
1209 || ExprHasProperty(p, EP_WinFunc)
1210 #endif
1212 nSize = EXPR_FULLSIZE;
1213 }else{
1214 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1215 assert( !ExprHasProperty(p, EP_FromJoin) );
1216 assert( !ExprHasProperty(p, EP_MemToken) );
1217 assert( !ExprHasVVAProperty(p, EP_NoReduce) );
1218 if( p->pLeft || p->x.pList ){
1219 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1220 }else{
1221 assert( p->pRight==0 );
1222 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1225 return nSize;
1229 ** This function returns the space in bytes required to store the copy
1230 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1231 ** string is defined.)
1233 static int dupedExprNodeSize(Expr *p, int flags){
1234 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1235 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1236 nByte += sqlite3Strlen30NN(p->u.zToken)+1;
1238 return ROUND8(nByte);
1242 ** Return the number of bytes required to create a duplicate of the
1243 ** expression passed as the first argument. The second argument is a
1244 ** mask containing EXPRDUP_XXX flags.
1246 ** The value returned includes space to create a copy of the Expr struct
1247 ** itself and the buffer referred to by Expr.u.zToken, if any.
1249 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
1250 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1251 ** and Expr.pRight variables (but not for any structures pointed to or
1252 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
1254 static int dupedExprSize(Expr *p, int flags){
1255 int nByte = 0;
1256 if( p ){
1257 nByte = dupedExprNodeSize(p, flags);
1258 if( flags&EXPRDUP_REDUCE ){
1259 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
1262 return nByte;
1266 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1267 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
1268 ** to store the copy of expression p, the copies of p->u.zToken
1269 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
1270 ** if any. Before returning, *pzBuffer is set to the first byte past the
1271 ** portion of the buffer copied into by this function.
1273 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1274 Expr *pNew; /* Value to return */
1275 u8 *zAlloc; /* Memory space from which to build Expr object */
1276 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1278 assert( db!=0 );
1279 assert( p );
1280 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1281 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
1283 /* Figure out where to write the new Expr structure. */
1284 if( pzBuffer ){
1285 zAlloc = *pzBuffer;
1286 staticFlag = EP_Static;
1287 }else{
1288 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1289 staticFlag = 0;
1291 pNew = (Expr *)zAlloc;
1293 if( pNew ){
1294 /* Set nNewSize to the size allocated for the structure pointed to
1295 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1296 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1297 ** by the copy of the p->u.zToken string (if any).
1299 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1300 const int nNewSize = nStructSize & 0xfff;
1301 int nToken;
1302 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1303 nToken = sqlite3Strlen30(p->u.zToken) + 1;
1304 }else{
1305 nToken = 0;
1307 if( dupFlags ){
1308 assert( ExprHasProperty(p, EP_Reduced)==0 );
1309 memcpy(zAlloc, p, nNewSize);
1310 }else{
1311 u32 nSize = (u32)exprStructSize(p);
1312 memcpy(zAlloc, p, nSize);
1313 if( nSize<EXPR_FULLSIZE ){
1314 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1318 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1319 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1320 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1321 pNew->flags |= staticFlag;
1322 ExprClearVVAProperties(pNew);
1323 if( dupFlags ){
1324 ExprSetVVAProperty(pNew, EP_Immutable);
1327 /* Copy the p->u.zToken string, if any. */
1328 if( nToken ){
1329 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1330 memcpy(zToken, p->u.zToken, nToken);
1333 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
1334 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1335 if( ExprHasProperty(p, EP_xIsSelect) ){
1336 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1337 }else{
1338 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1342 /* Fill in pNew->pLeft and pNew->pRight. */
1343 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
1344 zAlloc += dupedExprNodeSize(p, dupFlags);
1345 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
1346 pNew->pLeft = p->pLeft ?
1347 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1348 pNew->pRight = p->pRight ?
1349 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
1351 #ifndef SQLITE_OMIT_WINDOWFUNC
1352 if( ExprHasProperty(p, EP_WinFunc) ){
1353 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1354 assert( ExprHasProperty(pNew, EP_WinFunc) );
1356 #endif /* SQLITE_OMIT_WINDOWFUNC */
1357 if( pzBuffer ){
1358 *pzBuffer = zAlloc;
1360 }else{
1361 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1362 if( pNew->op==TK_SELECT_COLUMN ){
1363 pNew->pLeft = p->pLeft;
1364 assert( p->iColumn==0 || p->pRight==0 );
1365 assert( p->pRight==0 || p->pRight==p->pLeft );
1366 }else{
1367 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1369 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1373 return pNew;
1377 ** Create and return a deep copy of the object passed as the second
1378 ** argument. If an OOM condition is encountered, NULL is returned
1379 ** and the db->mallocFailed flag set.
1381 #ifndef SQLITE_OMIT_CTE
1382 static With *withDup(sqlite3 *db, With *p){
1383 With *pRet = 0;
1384 if( p ){
1385 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1386 pRet = sqlite3DbMallocZero(db, nByte);
1387 if( pRet ){
1388 int i;
1389 pRet->nCte = p->nCte;
1390 for(i=0; i<p->nCte; i++){
1391 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1392 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1393 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1397 return pRet;
1399 #else
1400 # define withDup(x,y) 0
1401 #endif
1403 #ifndef SQLITE_OMIT_WINDOWFUNC
1405 ** The gatherSelectWindows() procedure and its helper routine
1406 ** gatherSelectWindowsCallback() are used to scan all the expressions
1407 ** an a newly duplicated SELECT statement and gather all of the Window
1408 ** objects found there, assembling them onto the linked list at Select->pWin.
1410 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1411 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
1412 Select *pSelect = pWalker->u.pSelect;
1413 Window *pWin = pExpr->y.pWin;
1414 assert( pWin );
1415 assert( IsWindowFunc(pExpr) );
1416 assert( pWin->ppThis==0 );
1417 sqlite3WindowLink(pSelect, pWin);
1419 return WRC_Continue;
1421 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1422 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1424 static void gatherSelectWindows(Select *p){
1425 Walker w;
1426 w.xExprCallback = gatherSelectWindowsCallback;
1427 w.xSelectCallback = gatherSelectWindowsSelectCallback;
1428 w.xSelectCallback2 = 0;
1429 w.pParse = 0;
1430 w.u.pSelect = p;
1431 sqlite3WalkSelect(&w, p);
1433 #endif
1437 ** The following group of routines make deep copies of expressions,
1438 ** expression lists, ID lists, and select statements. The copies can
1439 ** be deleted (by being passed to their respective ...Delete() routines)
1440 ** without effecting the originals.
1442 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1443 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1444 ** by subsequent calls to sqlite*ListAppend() routines.
1446 ** Any tables that the SrcList might point to are not duplicated.
1448 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1449 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1450 ** truncated version of the usual Expr structure that will be stored as
1451 ** part of the in-memory representation of the database schema.
1453 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
1454 assert( flags==0 || flags==EXPRDUP_REDUCE );
1455 return p ? exprDup(db, p, flags, 0) : 0;
1457 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
1458 ExprList *pNew;
1459 struct ExprList_item *pItem, *pOldItem;
1460 int i;
1461 Expr *pPriorSelectCol = 0;
1462 assert( db!=0 );
1463 if( p==0 ) return 0;
1464 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1465 if( pNew==0 ) return 0;
1466 pNew->nExpr = p->nExpr;
1467 pItem = pNew->a;
1468 pOldItem = p->a;
1469 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1470 Expr *pOldExpr = pOldItem->pExpr;
1471 Expr *pNewExpr;
1472 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1473 if( pOldExpr
1474 && pOldExpr->op==TK_SELECT_COLUMN
1475 && (pNewExpr = pItem->pExpr)!=0
1477 assert( pNewExpr->iColumn==0 || i>0 );
1478 if( pNewExpr->iColumn==0 ){
1479 assert( pOldExpr->pLeft==pOldExpr->pRight );
1480 pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
1481 }else{
1482 assert( i>0 );
1483 assert( pItem[-1].pExpr!=0 );
1484 assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
1485 assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
1486 pNewExpr->pLeft = pPriorSelectCol;
1489 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
1490 pItem->sortFlags = pOldItem->sortFlags;
1491 pItem->eEName = pOldItem->eEName;
1492 pItem->done = 0;
1493 pItem->bNulls = pOldItem->bNulls;
1494 pItem->bSorterRef = pOldItem->bSorterRef;
1495 pItem->u = pOldItem->u;
1497 return pNew;
1501 ** If cursors, triggers, views and subqueries are all omitted from
1502 ** the build, then none of the following routines, except for
1503 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1504 ** called with a NULL argument.
1506 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1507 || !defined(SQLITE_OMIT_SUBQUERY)
1508 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1509 SrcList *pNew;
1510 int i;
1511 int nByte;
1512 assert( db!=0 );
1513 if( p==0 ) return 0;
1514 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1515 pNew = sqlite3DbMallocRawNN(db, nByte );
1516 if( pNew==0 ) return 0;
1517 pNew->nSrc = pNew->nAlloc = p->nSrc;
1518 for(i=0; i<p->nSrc; i++){
1519 struct SrcList_item *pNewItem = &pNew->a[i];
1520 struct SrcList_item *pOldItem = &p->a[i];
1521 Table *pTab;
1522 pNewItem->pSchema = pOldItem->pSchema;
1523 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1524 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1525 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1526 pNewItem->fg = pOldItem->fg;
1527 pNewItem->iCursor = pOldItem->iCursor;
1528 pNewItem->addrFillSub = pOldItem->addrFillSub;
1529 pNewItem->regReturn = pOldItem->regReturn;
1530 if( pNewItem->fg.isIndexedBy ){
1531 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1533 pNewItem->pIBIndex = pOldItem->pIBIndex;
1534 if( pNewItem->fg.isTabFunc ){
1535 pNewItem->u1.pFuncArg =
1536 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1538 pTab = pNewItem->pTab = pOldItem->pTab;
1539 if( pTab ){
1540 pTab->nTabRef++;
1542 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1543 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
1544 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
1545 pNewItem->colUsed = pOldItem->colUsed;
1547 return pNew;
1549 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1550 IdList *pNew;
1551 int i;
1552 assert( db!=0 );
1553 if( p==0 ) return 0;
1554 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1555 if( pNew==0 ) return 0;
1556 pNew->nId = p->nId;
1557 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
1558 if( pNew->a==0 ){
1559 sqlite3DbFreeNN(db, pNew);
1560 return 0;
1562 /* Note that because the size of the allocation for p->a[] is not
1563 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1564 ** on the duplicate created by this function. */
1565 for(i=0; i<p->nId; i++){
1566 struct IdList_item *pNewItem = &pNew->a[i];
1567 struct IdList_item *pOldItem = &p->a[i];
1568 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1569 pNewItem->idx = pOldItem->idx;
1571 return pNew;
1573 Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
1574 Select *pRet = 0;
1575 Select *pNext = 0;
1576 Select **pp = &pRet;
1577 Select *p;
1579 assert( db!=0 );
1580 for(p=pDup; p; p=p->pPrior){
1581 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1582 if( pNew==0 ) break;
1583 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1584 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1585 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1586 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1587 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1588 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1589 pNew->op = p->op;
1590 pNew->pNext = pNext;
1591 pNew->pPrior = 0;
1592 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1593 pNew->iLimit = 0;
1594 pNew->iOffset = 0;
1595 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1596 pNew->addrOpenEphm[0] = -1;
1597 pNew->addrOpenEphm[1] = -1;
1598 pNew->nSelectRow = p->nSelectRow;
1599 pNew->pWith = withDup(db, p->pWith);
1600 #ifndef SQLITE_OMIT_WINDOWFUNC
1601 pNew->pWin = 0;
1602 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1603 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
1604 #endif
1605 pNew->selId = p->selId;
1606 *pp = pNew;
1607 pp = &pNew->pPrior;
1608 pNext = pNew;
1611 return pRet;
1613 #else
1614 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
1615 assert( p==0 );
1616 return 0;
1618 #endif
1622 ** Add a new element to the end of an expression list. If pList is
1623 ** initially NULL, then create a new expression list.
1625 ** The pList argument must be either NULL or a pointer to an ExprList
1626 ** obtained from a prior call to sqlite3ExprListAppend(). This routine
1627 ** may not be used with an ExprList obtained from sqlite3ExprListDup().
1628 ** Reason: This routine assumes that the number of slots in pList->a[]
1629 ** is a power of two. That is true for sqlite3ExprListAppend() returns
1630 ** but is not necessarily true from the return value of sqlite3ExprListDup().
1632 ** If a memory allocation error occurs, the entire list is freed and
1633 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1634 ** that the new entry was successfully appended.
1636 ExprList *sqlite3ExprListAppend(
1637 Parse *pParse, /* Parsing context */
1638 ExprList *pList, /* List to which to append. Might be NULL */
1639 Expr *pExpr /* Expression to be appended. Might be NULL */
1641 struct ExprList_item *pItem;
1642 sqlite3 *db = pParse->db;
1643 assert( db!=0 );
1644 if( pList==0 ){
1645 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
1646 if( pList==0 ){
1647 goto no_mem;
1649 pList->nExpr = 0;
1650 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
1651 ExprList *pNew;
1652 pNew = sqlite3DbRealloc(db, pList,
1653 sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
1654 if( pNew==0 ){
1655 goto no_mem;
1657 pList = pNew;
1659 pItem = &pList->a[pList->nExpr++];
1660 assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) );
1661 assert( offsetof(struct ExprList_item,pExpr)==0 );
1662 memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName));
1663 pItem->pExpr = pExpr;
1664 return pList;
1666 no_mem:
1667 /* Avoid leaking memory if malloc has failed. */
1668 sqlite3ExprDelete(db, pExpr);
1669 sqlite3ExprListDelete(db, pList);
1670 return 0;
1674 ** pColumns and pExpr form a vector assignment which is part of the SET
1675 ** clause of an UPDATE statement. Like this:
1677 ** (a,b,c) = (expr1,expr2,expr3)
1678 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1680 ** For each term of the vector assignment, append new entries to the
1681 ** expression list pList. In the case of a subquery on the RHS, append
1682 ** TK_SELECT_COLUMN expressions.
1684 ExprList *sqlite3ExprListAppendVector(
1685 Parse *pParse, /* Parsing context */
1686 ExprList *pList, /* List to which to append. Might be NULL */
1687 IdList *pColumns, /* List of names of LHS of the assignment */
1688 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1690 sqlite3 *db = pParse->db;
1691 int n;
1692 int i;
1693 int iFirst = pList ? pList->nExpr : 0;
1694 /* pColumns can only be NULL due to an OOM but an OOM will cause an
1695 ** exit prior to this routine being invoked */
1696 if( NEVER(pColumns==0) ) goto vector_append_error;
1697 if( pExpr==0 ) goto vector_append_error;
1699 /* If the RHS is a vector, then we can immediately check to see that
1700 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
1701 ** wildcards ("*") in the result set of the SELECT must be expanded before
1702 ** we can do the size check, so defer the size check until code generation.
1704 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
1705 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1706 pColumns->nId, n);
1707 goto vector_append_error;
1710 for(i=0; i<pColumns->nId; i++){
1711 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1712 assert( pSubExpr!=0 || db->mallocFailed );
1713 assert( pSubExpr==0 || pSubExpr->iTable==0 );
1714 if( pSubExpr==0 ) continue;
1715 pSubExpr->iTable = pColumns->nId;
1716 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1717 if( pList ){
1718 assert( pList->nExpr==iFirst+i+1 );
1719 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
1720 pColumns->a[i].zName = 0;
1724 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
1725 Expr *pFirst = pList->a[iFirst].pExpr;
1726 assert( pFirst!=0 );
1727 assert( pFirst->op==TK_SELECT_COLUMN );
1729 /* Store the SELECT statement in pRight so it will be deleted when
1730 ** sqlite3ExprListDelete() is called */
1731 pFirst->pRight = pExpr;
1732 pExpr = 0;
1734 /* Remember the size of the LHS in iTable so that we can check that
1735 ** the RHS and LHS sizes match during code generation. */
1736 pFirst->iTable = pColumns->nId;
1739 vector_append_error:
1740 sqlite3ExprUnmapAndDelete(pParse, pExpr);
1741 sqlite3IdListDelete(db, pColumns);
1742 return pList;
1746 ** Set the sort order for the last element on the given ExprList.
1748 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
1749 struct ExprList_item *pItem;
1750 if( p==0 ) return;
1751 assert( p->nExpr>0 );
1753 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
1754 assert( iSortOrder==SQLITE_SO_UNDEFINED
1755 || iSortOrder==SQLITE_SO_ASC
1756 || iSortOrder==SQLITE_SO_DESC
1758 assert( eNulls==SQLITE_SO_UNDEFINED
1759 || eNulls==SQLITE_SO_ASC
1760 || eNulls==SQLITE_SO_DESC
1763 pItem = &p->a[p->nExpr-1];
1764 assert( pItem->bNulls==0 );
1765 if( iSortOrder==SQLITE_SO_UNDEFINED ){
1766 iSortOrder = SQLITE_SO_ASC;
1768 pItem->sortFlags = (u8)iSortOrder;
1770 if( eNulls!=SQLITE_SO_UNDEFINED ){
1771 pItem->bNulls = 1;
1772 if( iSortOrder!=eNulls ){
1773 pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
1779 ** Set the ExprList.a[].zEName element of the most recently added item
1780 ** on the expression list.
1782 ** pList might be NULL following an OOM error. But pName should never be
1783 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1784 ** is set.
1786 void sqlite3ExprListSetName(
1787 Parse *pParse, /* Parsing context */
1788 ExprList *pList, /* List to which to add the span. */
1789 Token *pName, /* Name to be added */
1790 int dequote /* True to cause the name to be dequoted */
1792 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1793 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
1794 if( pList ){
1795 struct ExprList_item *pItem;
1796 assert( pList->nExpr>0 );
1797 pItem = &pList->a[pList->nExpr-1];
1798 assert( pItem->zEName==0 );
1799 assert( pItem->eEName==ENAME_NAME );
1800 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1801 if( dequote ){
1802 /* If dequote==0, then pName->z does not point to part of a DDL
1803 ** statement handled by the parser. And so no token need be added
1804 ** to the token-map. */
1805 sqlite3Dequote(pItem->zEName);
1806 if( IN_RENAME_OBJECT ){
1807 sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName);
1814 ** Set the ExprList.a[].zSpan element of the most recently added item
1815 ** on the expression list.
1817 ** pList might be NULL following an OOM error. But pSpan should never be
1818 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1819 ** is set.
1821 void sqlite3ExprListSetSpan(
1822 Parse *pParse, /* Parsing context */
1823 ExprList *pList, /* List to which to add the span. */
1824 const char *zStart, /* Start of the span */
1825 const char *zEnd /* End of the span */
1827 sqlite3 *db = pParse->db;
1828 assert( pList!=0 || db->mallocFailed!=0 );
1829 if( pList ){
1830 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1831 assert( pList->nExpr>0 );
1832 if( pItem->zEName==0 ){
1833 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
1834 pItem->eEName = ENAME_SPAN;
1840 ** If the expression list pEList contains more than iLimit elements,
1841 ** leave an error message in pParse.
1843 void sqlite3ExprListCheckLength(
1844 Parse *pParse,
1845 ExprList *pEList,
1846 const char *zObject
1848 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1849 testcase( pEList && pEList->nExpr==mx );
1850 testcase( pEList && pEList->nExpr==mx+1 );
1851 if( pEList && pEList->nExpr>mx ){
1852 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1857 ** Delete an entire expression list.
1859 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
1860 int i = pList->nExpr;
1861 struct ExprList_item *pItem = pList->a;
1862 assert( pList->nExpr>0 );
1864 sqlite3ExprDelete(db, pItem->pExpr);
1865 sqlite3DbFree(db, pItem->zEName);
1866 pItem++;
1867 }while( --i>0 );
1868 sqlite3DbFreeNN(db, pList);
1870 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1871 if( pList ) exprListDeleteNN(db, pList);
1875 ** Return the bitwise-OR of all Expr.flags fields in the given
1876 ** ExprList.
1878 u32 sqlite3ExprListFlags(const ExprList *pList){
1879 int i;
1880 u32 m = 0;
1881 assert( pList!=0 );
1882 for(i=0; i<pList->nExpr; i++){
1883 Expr *pExpr = pList->a[i].pExpr;
1884 assert( pExpr!=0 );
1885 m |= pExpr->flags;
1887 return m;
1891 ** This is a SELECT-node callback for the expression walker that
1892 ** always "fails". By "fail" in this case, we mean set
1893 ** pWalker->eCode to zero and abort.
1895 ** This callback is used by multiple expression walkers.
1897 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
1898 UNUSED_PARAMETER(NotUsed);
1899 pWalker->eCode = 0;
1900 return WRC_Abort;
1904 ** Check the input string to see if it is "true" or "false" (in any case).
1906 ** If the string is.... Return
1907 ** "true" EP_IsTrue
1908 ** "false" EP_IsFalse
1909 ** anything else 0
1911 u32 sqlite3IsTrueOrFalse(const char *zIn){
1912 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue;
1913 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
1914 return 0;
1919 ** If the input expression is an ID with the name "true" or "false"
1920 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
1921 ** the conversion happened, and zero if the expression is unaltered.
1923 int sqlite3ExprIdToTrueFalse(Expr *pExpr){
1924 u32 v;
1925 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
1926 if( !ExprHasProperty(pExpr, EP_Quoted)
1927 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
1929 pExpr->op = TK_TRUEFALSE;
1930 ExprSetProperty(pExpr, v);
1931 return 1;
1933 return 0;
1937 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
1938 ** and 0 if it is FALSE.
1940 int sqlite3ExprTruthValue(const Expr *pExpr){
1941 pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
1942 assert( pExpr->op==TK_TRUEFALSE );
1943 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
1944 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
1945 return pExpr->u.zToken[4]==0;
1949 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
1950 ** terms that are always true or false. Return the simplified expression.
1951 ** Or return the original expression if no simplification is possible.
1953 ** Examples:
1955 ** (x<10) AND true => (x<10)
1956 ** (x<10) AND false => false
1957 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
1958 ** (x<10) AND (y=22 OR true) => (x<10)
1959 ** (y=22) OR true => true
1961 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
1962 assert( pExpr!=0 );
1963 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
1964 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
1965 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
1966 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
1967 pExpr = pExpr->op==TK_AND ? pRight : pLeft;
1968 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
1969 pExpr = pExpr->op==TK_AND ? pLeft : pRight;
1972 return pExpr;
1977 ** These routines are Walker callbacks used to check expressions to
1978 ** see if they are "constant" for some definition of constant. The
1979 ** Walker.eCode value determines the type of "constant" we are looking
1980 ** for.
1982 ** These callback routines are used to implement the following:
1984 ** sqlite3ExprIsConstant() pWalker->eCode==1
1985 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
1986 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
1987 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
1989 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1990 ** is found to not be a constant.
1992 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
1993 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
1994 ** when parsing an existing schema out of the sqlite_schema table and 4
1995 ** when processing a new CREATE TABLE statement. A bound parameter raises
1996 ** an error for new statements, but is silently converted
1997 ** to NULL for existing schemas. This allows sqlite_schema tables that
1998 ** contain a bound parameter because they were generated by older versions
1999 ** of SQLite to be parsed by newer versions of SQLite without raising a
2000 ** malformed schema error.
2002 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
2004 /* If pWalker->eCode is 2 then any term of the expression that comes from
2005 ** the ON or USING clauses of a left join disqualifies the expression
2006 ** from being considered constant. */
2007 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
2008 pWalker->eCode = 0;
2009 return WRC_Abort;
2012 switch( pExpr->op ){
2013 /* Consider functions to be constant if all their arguments are constant
2014 ** and either pWalker->eCode==4 or 5 or the function has the
2015 ** SQLITE_FUNC_CONST flag. */
2016 case TK_FUNCTION:
2017 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
2018 && !ExprHasProperty(pExpr, EP_WinFunc)
2020 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
2021 return WRC_Continue;
2022 }else{
2023 pWalker->eCode = 0;
2024 return WRC_Abort;
2026 case TK_ID:
2027 /* Convert "true" or "false" in a DEFAULT clause into the
2028 ** appropriate TK_TRUEFALSE operator */
2029 if( sqlite3ExprIdToTrueFalse(pExpr) ){
2030 return WRC_Prune;
2032 /* no break */ deliberate_fall_through
2033 case TK_COLUMN:
2034 case TK_AGG_FUNCTION:
2035 case TK_AGG_COLUMN:
2036 testcase( pExpr->op==TK_ID );
2037 testcase( pExpr->op==TK_COLUMN );
2038 testcase( pExpr->op==TK_AGG_FUNCTION );
2039 testcase( pExpr->op==TK_AGG_COLUMN );
2040 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
2041 return WRC_Continue;
2043 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
2044 return WRC_Continue;
2046 /* no break */ deliberate_fall_through
2047 case TK_IF_NULL_ROW:
2048 case TK_REGISTER:
2049 case TK_DOT:
2050 testcase( pExpr->op==TK_REGISTER );
2051 testcase( pExpr->op==TK_IF_NULL_ROW );
2052 testcase( pExpr->op==TK_DOT );
2053 pWalker->eCode = 0;
2054 return WRC_Abort;
2055 case TK_VARIABLE:
2056 if( pWalker->eCode==5 ){
2057 /* Silently convert bound parameters that appear inside of CREATE
2058 ** statements into a NULL when parsing the CREATE statement text out
2059 ** of the sqlite_schema table */
2060 pExpr->op = TK_NULL;
2061 }else if( pWalker->eCode==4 ){
2062 /* A bound parameter in a CREATE statement that originates from
2063 ** sqlite3_prepare() causes an error */
2064 pWalker->eCode = 0;
2065 return WRC_Abort;
2067 /* no break */ deliberate_fall_through
2068 default:
2069 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
2070 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
2071 return WRC_Continue;
2074 static int exprIsConst(Expr *p, int initFlag, int iCur){
2075 Walker w;
2076 w.eCode = initFlag;
2077 w.xExprCallback = exprNodeIsConstant;
2078 w.xSelectCallback = sqlite3SelectWalkFail;
2079 #ifdef SQLITE_DEBUG
2080 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2081 #endif
2082 w.u.iCur = iCur;
2083 sqlite3WalkExpr(&w, p);
2084 return w.eCode;
2088 ** Walk an expression tree. Return non-zero if the expression is constant
2089 ** and 0 if it involves variables or function calls.
2091 ** For the purposes of this function, a double-quoted string (ex: "abc")
2092 ** is considered a variable but a single-quoted string (ex: 'abc') is
2093 ** a constant.
2095 int sqlite3ExprIsConstant(Expr *p){
2096 return exprIsConst(p, 1, 0);
2100 ** Walk an expression tree. Return non-zero if
2102 ** (1) the expression is constant, and
2103 ** (2) the expression does originate in the ON or USING clause
2104 ** of a LEFT JOIN, and
2105 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2106 ** operands created by the constant propagation optimization.
2108 ** When this routine returns true, it indicates that the expression
2109 ** can be added to the pParse->pConstExpr list and evaluated once when
2110 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2112 int sqlite3ExprIsConstantNotJoin(Expr *p){
2113 return exprIsConst(p, 2, 0);
2117 ** Walk an expression tree. Return non-zero if the expression is constant
2118 ** for any single row of the table with cursor iCur. In other words, the
2119 ** expression must not refer to any non-deterministic function nor any
2120 ** table other than iCur.
2122 int sqlite3ExprIsTableConstant(Expr *p, int iCur){
2123 return exprIsConst(p, 3, iCur);
2128 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2130 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2131 ExprList *pGroupBy = pWalker->u.pGroupBy;
2132 int i;
2134 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2135 ** it constant. */
2136 for(i=0; i<pGroupBy->nExpr; i++){
2137 Expr *p = pGroupBy->a[i].pExpr;
2138 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
2139 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2140 if( sqlite3IsBinary(pColl) ){
2141 return WRC_Prune;
2146 /* Check if pExpr is a sub-select. If so, consider it variable. */
2147 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2148 pWalker->eCode = 0;
2149 return WRC_Abort;
2152 return exprNodeIsConstant(pWalker, pExpr);
2156 ** Walk the expression tree passed as the first argument. Return non-zero
2157 ** if the expression consists entirely of constants or copies of terms
2158 ** in pGroupBy that sort with the BINARY collation sequence.
2160 ** This routine is used to determine if a term of the HAVING clause can
2161 ** be promoted into the WHERE clause. In order for such a promotion to work,
2162 ** the value of the HAVING clause term must be the same for all members of
2163 ** a "group". The requirement that the GROUP BY term must be BINARY
2164 ** assumes that no other collating sequence will have a finer-grained
2165 ** grouping than binary. In other words (A=B COLLATE binary) implies
2166 ** A=B in every other collating sequence. The requirement that the
2167 ** GROUP BY be BINARY is stricter than necessary. It would also work
2168 ** to promote HAVING clauses that use the same alternative collating
2169 ** sequence as the GROUP BY term, but that is much harder to check,
2170 ** alternative collating sequences are uncommon, and this is only an
2171 ** optimization, so we take the easy way out and simply require the
2172 ** GROUP BY to use the BINARY collating sequence.
2174 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2175 Walker w;
2176 w.eCode = 1;
2177 w.xExprCallback = exprNodeIsConstantOrGroupBy;
2178 w.xSelectCallback = 0;
2179 w.u.pGroupBy = pGroupBy;
2180 w.pParse = pParse;
2181 sqlite3WalkExpr(&w, p);
2182 return w.eCode;
2186 ** Walk an expression tree for the DEFAULT field of a column definition
2187 ** in a CREATE TABLE statement. Return non-zero if the expression is
2188 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2189 ** the expression is constant or a function call with constant arguments.
2190 ** Return and 0 if there are any variables.
2192 ** isInit is true when parsing from sqlite_schema. isInit is false when
2193 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2194 ** (such as ? or $abc) in the expression are converted into NULL. When
2195 ** isInit is false, parameters raise an error. Parameters should not be
2196 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2197 ** allowed it, so we need to support it when reading sqlite_schema for
2198 ** backwards compatibility.
2200 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2202 ** For the purposes of this function, a double-quoted string (ex: "abc")
2203 ** is considered a variable but a single-quoted string (ex: 'abc') is
2204 ** a constant.
2206 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2207 assert( isInit==0 || isInit==1 );
2208 return exprIsConst(p, 4+isInit, 0);
2211 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2213 ** Walk an expression tree. Return 1 if the expression contains a
2214 ** subquery of some kind. Return 0 if there are no subqueries.
2216 int sqlite3ExprContainsSubquery(Expr *p){
2217 Walker w;
2218 w.eCode = 1;
2219 w.xExprCallback = sqlite3ExprWalkNoop;
2220 w.xSelectCallback = sqlite3SelectWalkFail;
2221 #ifdef SQLITE_DEBUG
2222 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2223 #endif
2224 sqlite3WalkExpr(&w, p);
2225 return w.eCode==0;
2227 #endif
2230 ** If the expression p codes a constant integer that is small enough
2231 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2232 ** in *pValue. If the expression is not an integer or if it is too big
2233 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2235 int sqlite3ExprIsInteger(Expr *p, int *pValue){
2236 int rc = 0;
2237 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
2239 /* If an expression is an integer literal that fits in a signed 32-bit
2240 ** integer, then the EP_IntValue flag will have already been set */
2241 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2242 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2244 if( p->flags & EP_IntValue ){
2245 *pValue = p->u.iValue;
2246 return 1;
2248 switch( p->op ){
2249 case TK_UPLUS: {
2250 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
2251 break;
2253 case TK_UMINUS: {
2254 int v;
2255 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
2256 assert( v!=(-2147483647-1) );
2257 *pValue = -v;
2258 rc = 1;
2260 break;
2262 default: break;
2264 return rc;
2268 ** Return FALSE if there is no chance that the expression can be NULL.
2270 ** If the expression might be NULL or if the expression is too complex
2271 ** to tell return TRUE.
2273 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2274 ** when we know that a value cannot be NULL. Hence, a false positive
2275 ** (returning TRUE when in fact the expression can never be NULL) might
2276 ** be a small performance hit but is otherwise harmless. On the other
2277 ** hand, a false negative (returning FALSE when the result could be NULL)
2278 ** will likely result in an incorrect answer. So when in doubt, return
2279 ** TRUE.
2281 int sqlite3ExprCanBeNull(const Expr *p){
2282 u8 op;
2283 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2284 p = p->pLeft;
2286 op = p->op;
2287 if( op==TK_REGISTER ) op = p->op2;
2288 switch( op ){
2289 case TK_INTEGER:
2290 case TK_STRING:
2291 case TK_FLOAT:
2292 case TK_BLOB:
2293 return 0;
2294 case TK_COLUMN:
2295 return ExprHasProperty(p, EP_CanBeNull) ||
2296 p->y.pTab==0 || /* Reference to column of index on expression */
2297 (p->iColumn>=0
2298 && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */
2299 && p->y.pTab->aCol[p->iColumn].notNull==0);
2300 default:
2301 return 1;
2306 ** Return TRUE if the given expression is a constant which would be
2307 ** unchanged by OP_Affinity with the affinity given in the second
2308 ** argument.
2310 ** This routine is used to determine if the OP_Affinity operation
2311 ** can be omitted. When in doubt return FALSE. A false negative
2312 ** is harmless. A false positive, however, can result in the wrong
2313 ** answer.
2315 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2316 u8 op;
2317 int unaryMinus = 0;
2318 if( aff==SQLITE_AFF_BLOB ) return 1;
2319 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2320 if( p->op==TK_UMINUS ) unaryMinus = 1;
2321 p = p->pLeft;
2323 op = p->op;
2324 if( op==TK_REGISTER ) op = p->op2;
2325 switch( op ){
2326 case TK_INTEGER: {
2327 return aff>=SQLITE_AFF_NUMERIC;
2329 case TK_FLOAT: {
2330 return aff>=SQLITE_AFF_NUMERIC;
2332 case TK_STRING: {
2333 return !unaryMinus && aff==SQLITE_AFF_TEXT;
2335 case TK_BLOB: {
2336 return !unaryMinus;
2338 case TK_COLUMN: {
2339 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
2340 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
2342 default: {
2343 return 0;
2349 ** Return TRUE if the given string is a row-id column name.
2351 int sqlite3IsRowid(const char *z){
2352 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2353 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2354 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2355 return 0;
2359 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2360 ** that can be simplified to a direct table access, then return
2361 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2362 ** or if the SELECT statement needs to be manifested into a transient
2363 ** table, then return NULL.
2365 #ifndef SQLITE_OMIT_SUBQUERY
2366 static Select *isCandidateForInOpt(Expr *pX){
2367 Select *p;
2368 SrcList *pSrc;
2369 ExprList *pEList;
2370 Table *pTab;
2371 int i;
2372 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
2373 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
2374 p = pX->x.pSelect;
2375 if( p->pPrior ) return 0; /* Not a compound SELECT */
2376 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2377 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2378 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2379 return 0; /* No DISTINCT keyword and no aggregate functions */
2381 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
2382 if( p->pLimit ) return 0; /* Has no LIMIT clause */
2383 if( p->pWhere ) return 0; /* Has no WHERE clause */
2384 pSrc = p->pSrc;
2385 assert( pSrc!=0 );
2386 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
2387 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
2388 pTab = pSrc->a[0].pTab;
2389 assert( pTab!=0 );
2390 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
2391 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
2392 pEList = p->pEList;
2393 assert( pEList!=0 );
2394 /* All SELECT results must be columns. */
2395 for(i=0; i<pEList->nExpr; i++){
2396 Expr *pRes = pEList->a[i].pExpr;
2397 if( pRes->op!=TK_COLUMN ) return 0;
2398 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
2400 return p;
2402 #endif /* SQLITE_OMIT_SUBQUERY */
2404 #ifndef SQLITE_OMIT_SUBQUERY
2406 ** Generate code that checks the left-most column of index table iCur to see if
2407 ** it contains any NULL entries. Cause the register at regHasNull to be set
2408 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2409 ** to be set to NULL if iCur contains one or more NULL values.
2411 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2412 int addr1;
2413 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2414 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2415 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2416 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
2417 VdbeComment((v, "first_entry_in(%d)", iCur));
2418 sqlite3VdbeJumpHere(v, addr1);
2420 #endif
2423 #ifndef SQLITE_OMIT_SUBQUERY
2425 ** The argument is an IN operator with a list (not a subquery) on the
2426 ** right-hand side. Return TRUE if that list is constant.
2428 static int sqlite3InRhsIsConstant(Expr *pIn){
2429 Expr *pLHS;
2430 int res;
2431 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2432 pLHS = pIn->pLeft;
2433 pIn->pLeft = 0;
2434 res = sqlite3ExprIsConstant(pIn);
2435 pIn->pLeft = pLHS;
2436 return res;
2438 #endif
2441 ** This function is used by the implementation of the IN (...) operator.
2442 ** The pX parameter is the expression on the RHS of the IN operator, which
2443 ** might be either a list of expressions or a subquery.
2445 ** The job of this routine is to find or create a b-tree object that can
2446 ** be used either to test for membership in the RHS set or to iterate through
2447 ** all members of the RHS set, skipping duplicates.
2449 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2450 ** and pX->iTable is set to the index of that cursor.
2452 ** The returned value of this function indicates the b-tree type, as follows:
2454 ** IN_INDEX_ROWID - The cursor was opened on a database table.
2455 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2456 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2457 ** IN_INDEX_EPH - The cursor was opened on a specially created and
2458 ** populated epheremal table.
2459 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2460 ** implemented as a sequence of comparisons.
2462 ** An existing b-tree might be used if the RHS expression pX is a simple
2463 ** subquery such as:
2465 ** SELECT <column1>, <column2>... FROM <table>
2467 ** If the RHS of the IN operator is a list or a more complex subquery, then
2468 ** an ephemeral table might need to be generated from the RHS and then
2469 ** pX->iTable made to point to the ephemeral table instead of an
2470 ** existing table.
2472 ** The inFlags parameter must contain, at a minimum, one of the bits
2473 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2474 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2475 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2476 ** be used to loop over all values of the RHS of the IN operator.
2478 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2479 ** through the set members) then the b-tree must not contain duplicates.
2480 ** An epheremal table will be created unless the selected columns are guaranteed
2481 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2482 ** a UNIQUE constraint or index.
2484 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2485 ** for fast set membership tests) then an epheremal table must
2486 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2487 ** index can be found with the specified <columns> as its left-most.
2489 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2490 ** if the RHS of the IN operator is a list (not a subquery) then this
2491 ** routine might decide that creating an ephemeral b-tree for membership
2492 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2493 ** calling routine should implement the IN operator using a sequence
2494 ** of Eq or Ne comparison operations.
2496 ** When the b-tree is being used for membership tests, the calling function
2497 ** might need to know whether or not the RHS side of the IN operator
2498 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
2499 ** if there is any chance that the (...) might contain a NULL value at
2500 ** runtime, then a register is allocated and the register number written
2501 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2502 ** NULL value, then *prRhsHasNull is left unchanged.
2504 ** If a register is allocated and its location stored in *prRhsHasNull, then
2505 ** the value in that register will be NULL if the b-tree contains one or more
2506 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2507 ** NULL values.
2509 ** If the aiMap parameter is not NULL, it must point to an array containing
2510 ** one element for each column returned by the SELECT statement on the RHS
2511 ** of the IN(...) operator. The i'th entry of the array is populated with the
2512 ** offset of the index column that matches the i'th column returned by the
2513 ** SELECT. For example, if the expression and selected index are:
2515 ** (?,?,?) IN (SELECT a, b, c FROM t1)
2516 ** CREATE INDEX i1 ON t1(b, c, a);
2518 ** then aiMap[] is populated with {2, 0, 1}.
2520 #ifndef SQLITE_OMIT_SUBQUERY
2521 int sqlite3FindInIndex(
2522 Parse *pParse, /* Parsing context */
2523 Expr *pX, /* The IN expression */
2524 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2525 int *prRhsHasNull, /* Register holding NULL status. See notes */
2526 int *aiMap, /* Mapping from Index fields to RHS fields */
2527 int *piTab /* OUT: index to use */
2529 Select *p; /* SELECT to the right of IN operator */
2530 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2531 int iTab = pParse->nTab++; /* Cursor of the RHS table */
2532 int mustBeUnique; /* True if RHS must be unique */
2533 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
2535 assert( pX->op==TK_IN );
2536 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
2538 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2539 ** whether or not the SELECT result contains NULL values, check whether
2540 ** or not NULL is actually possible (it may not be, for example, due
2541 ** to NOT NULL constraints in the schema). If no NULL values are possible,
2542 ** set prRhsHasNull to 0 before continuing. */
2543 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2544 int i;
2545 ExprList *pEList = pX->x.pSelect->pEList;
2546 for(i=0; i<pEList->nExpr; i++){
2547 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2549 if( i==pEList->nExpr ){
2550 prRhsHasNull = 0;
2554 /* Check to see if an existing table or index can be used to
2555 ** satisfy the query. This is preferable to generating a new
2556 ** ephemeral table. */
2557 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
2558 sqlite3 *db = pParse->db; /* Database connection */
2559 Table *pTab; /* Table <table>. */
2560 int iDb; /* Database idx for pTab */
2561 ExprList *pEList = p->pEList;
2562 int nExpr = pEList->nExpr;
2564 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2565 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2566 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2567 pTab = p->pSrc->a[0].pTab;
2569 /* Code an OP_Transaction and OP_TableLock for <table>. */
2570 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2571 assert( iDb>=0 && iDb<SQLITE_MAX_ATTACHED );
2572 sqlite3CodeVerifySchema(pParse, iDb);
2573 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
2575 assert(v); /* sqlite3GetVdbe() has always been previously called */
2576 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
2577 /* The "x IN (SELECT rowid FROM table)" case */
2578 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
2579 VdbeCoverage(v);
2581 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2582 eType = IN_INDEX_ROWID;
2583 ExplainQueryPlan((pParse, 0,
2584 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
2585 sqlite3VdbeJumpHere(v, iAddr);
2586 }else{
2587 Index *pIdx; /* Iterator variable */
2588 int affinity_ok = 1;
2589 int i;
2591 /* Check that the affinity that will be used to perform each
2592 ** comparison is the same as the affinity of each column in table
2593 ** on the RHS of the IN operator. If it not, it is not possible to
2594 ** use any index of the RHS table. */
2595 for(i=0; i<nExpr && affinity_ok; i++){
2596 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2597 int iCol = pEList->a[i].pExpr->iColumn;
2598 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
2599 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2600 testcase( cmpaff==SQLITE_AFF_BLOB );
2601 testcase( cmpaff==SQLITE_AFF_TEXT );
2602 switch( cmpaff ){
2603 case SQLITE_AFF_BLOB:
2604 break;
2605 case SQLITE_AFF_TEXT:
2606 /* sqlite3CompareAffinity() only returns TEXT if one side or the
2607 ** other has no affinity and the other side is TEXT. Hence,
2608 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2609 ** and for the term on the LHS of the IN to have no affinity. */
2610 assert( idxaff==SQLITE_AFF_TEXT );
2611 break;
2612 default:
2613 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2617 if( affinity_ok ){
2618 /* Search for an existing index that will work for this IN operator */
2619 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2620 Bitmask colUsed; /* Columns of the index used */
2621 Bitmask mCol; /* Mask for the current column */
2622 if( pIdx->nColumn<nExpr ) continue;
2623 if( pIdx->pPartIdxWhere!=0 ) continue;
2624 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2625 ** BITMASK(nExpr) without overflowing */
2626 testcase( pIdx->nColumn==BMS-2 );
2627 testcase( pIdx->nColumn==BMS-1 );
2628 if( pIdx->nColumn>=BMS-1 ) continue;
2629 if( mustBeUnique ){
2630 if( pIdx->nKeyCol>nExpr
2631 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2633 continue; /* This index is not unique over the IN RHS columns */
2637 colUsed = 0; /* Columns of index used so far */
2638 for(i=0; i<nExpr; i++){
2639 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2640 Expr *pRhs = pEList->a[i].pExpr;
2641 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2642 int j;
2644 assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
2645 for(j=0; j<nExpr; j++){
2646 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2647 assert( pIdx->azColl[j] );
2648 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2649 continue;
2651 break;
2653 if( j==nExpr ) break;
2654 mCol = MASKBIT(j);
2655 if( mCol & colUsed ) break; /* Each column used only once */
2656 colUsed |= mCol;
2657 if( aiMap ) aiMap[i] = j;
2660 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2661 if( colUsed==(MASKBIT(nExpr)-1) ){
2662 /* If we reach this point, that means the index pIdx is usable */
2663 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2664 ExplainQueryPlan((pParse, 0,
2665 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
2666 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2667 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2668 VdbeComment((v, "%s", pIdx->zName));
2669 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2670 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
2672 if( prRhsHasNull ){
2673 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
2674 i64 mask = (1<<nExpr)-1;
2675 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
2676 iTab, 0, 0, (u8*)&mask, P4_INT64);
2677 #endif
2678 *prRhsHasNull = ++pParse->nMem;
2679 if( nExpr==1 ){
2680 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2683 sqlite3VdbeJumpHere(v, iAddr);
2685 } /* End loop over indexes */
2686 } /* End if( affinity_ok ) */
2687 } /* End if not an rowid index */
2688 } /* End attempt to optimize using an index */
2690 /* If no preexisting index is available for the IN clause
2691 ** and IN_INDEX_NOOP is an allowed reply
2692 ** and the RHS of the IN operator is a list, not a subquery
2693 ** and the RHS is not constant or has two or fewer terms,
2694 ** then it is not worth creating an ephemeral table to evaluate
2695 ** the IN operator so return IN_INDEX_NOOP.
2697 if( eType==0
2698 && (inFlags & IN_INDEX_NOOP_OK)
2699 && !ExprHasProperty(pX, EP_xIsSelect)
2700 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2702 eType = IN_INDEX_NOOP;
2705 if( eType==0 ){
2706 /* Could not find an existing table or index to use as the RHS b-tree.
2707 ** We will have to generate an ephemeral table to do the job.
2709 u32 savedNQueryLoop = pParse->nQueryLoop;
2710 int rMayHaveNull = 0;
2711 eType = IN_INDEX_EPH;
2712 if( inFlags & IN_INDEX_LOOP ){
2713 pParse->nQueryLoop = 0;
2714 }else if( prRhsHasNull ){
2715 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
2717 assert( pX->op==TK_IN );
2718 sqlite3CodeRhsOfIN(pParse, pX, iTab);
2719 if( rMayHaveNull ){
2720 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
2722 pParse->nQueryLoop = savedNQueryLoop;
2725 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2726 int i, n;
2727 n = sqlite3ExprVectorSize(pX->pLeft);
2728 for(i=0; i<n; i++) aiMap[i] = i;
2730 *piTab = iTab;
2731 return eType;
2733 #endif
2735 #ifndef SQLITE_OMIT_SUBQUERY
2737 ** Argument pExpr is an (?, ?...) IN(...) expression. This
2738 ** function allocates and returns a nul-terminated string containing
2739 ** the affinities to be used for each column of the comparison.
2741 ** It is the responsibility of the caller to ensure that the returned
2742 ** string is eventually freed using sqlite3DbFree().
2744 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2745 Expr *pLeft = pExpr->pLeft;
2746 int nVal = sqlite3ExprVectorSize(pLeft);
2747 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
2748 char *zRet;
2750 assert( pExpr->op==TK_IN );
2751 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
2752 if( zRet ){
2753 int i;
2754 for(i=0; i<nVal; i++){
2755 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
2756 char a = sqlite3ExprAffinity(pA);
2757 if( pSelect ){
2758 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2759 }else{
2760 zRet[i] = a;
2763 zRet[nVal] = '\0';
2765 return zRet;
2767 #endif
2769 #ifndef SQLITE_OMIT_SUBQUERY
2771 ** Load the Parse object passed as the first argument with an error
2772 ** message of the form:
2774 ** "sub-select returns N columns - expected M"
2776 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2777 if( pParse->nErr==0 ){
2778 const char *zFmt = "sub-select returns %d columns - expected %d";
2779 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2782 #endif
2785 ** Expression pExpr is a vector that has been used in a context where
2786 ** it is not permitted. If pExpr is a sub-select vector, this routine
2787 ** loads the Parse object with a message of the form:
2789 ** "sub-select returns N columns - expected 1"
2791 ** Or, if it is a regular scalar vector:
2793 ** "row value misused"
2795 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
2796 #ifndef SQLITE_OMIT_SUBQUERY
2797 if( pExpr->flags & EP_xIsSelect ){
2798 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
2799 }else
2800 #endif
2802 sqlite3ErrorMsg(pParse, "row value misused");
2806 #ifndef SQLITE_OMIT_SUBQUERY
2808 ** Generate code that will construct an ephemeral table containing all terms
2809 ** in the RHS of an IN operator. The IN operator can be in either of two
2810 ** forms:
2812 ** x IN (4,5,11) -- IN operator with list on right-hand side
2813 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
2815 ** The pExpr parameter is the IN operator. The cursor number for the
2816 ** constructed ephermeral table is returned. The first time the ephemeral
2817 ** table is computed, the cursor number is also stored in pExpr->iTable,
2818 ** however the cursor number returned might not be the same, as it might
2819 ** have been duplicated using OP_OpenDup.
2821 ** If the LHS expression ("x" in the examples) is a column value, or
2822 ** the SELECT statement returns a column value, then the affinity of that
2823 ** column is used to build the index keys. If both 'x' and the
2824 ** SELECT... statement are columns, then numeric affinity is used
2825 ** if either column has NUMERIC or INTEGER affinity. If neither
2826 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2827 ** is used.
2829 void sqlite3CodeRhsOfIN(
2830 Parse *pParse, /* Parsing context */
2831 Expr *pExpr, /* The IN operator */
2832 int iTab /* Use this cursor number */
2834 int addrOnce = 0; /* Address of the OP_Once instruction at top */
2835 int addr; /* Address of OP_OpenEphemeral instruction */
2836 Expr *pLeft; /* the LHS of the IN operator */
2837 KeyInfo *pKeyInfo = 0; /* Key information */
2838 int nVal; /* Size of vector pLeft */
2839 Vdbe *v; /* The prepared statement under construction */
2841 v = pParse->pVdbe;
2842 assert( v!=0 );
2844 /* The evaluation of the IN must be repeated every time it
2845 ** is encountered if any of the following is true:
2847 ** * The right-hand side is a correlated subquery
2848 ** * The right-hand side is an expression list containing variables
2849 ** * We are inside a trigger
2851 ** If all of the above are false, then we can compute the RHS just once
2852 ** and reuse it many names.
2854 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
2855 /* Reuse of the RHS is allowed */
2856 /* If this routine has already been coded, but the previous code
2857 ** might not have been invoked yet, so invoke it now as a subroutine.
2859 if( ExprHasProperty(pExpr, EP_Subrtn) ){
2860 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2861 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2862 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
2863 pExpr->x.pSelect->selId));
2865 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
2866 pExpr->y.sub.iAddr);
2867 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
2868 sqlite3VdbeJumpHere(v, addrOnce);
2869 return;
2872 /* Begin coding the subroutine */
2873 ExprSetProperty(pExpr, EP_Subrtn);
2874 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
2875 pExpr->y.sub.regReturn = ++pParse->nMem;
2876 pExpr->y.sub.iAddr =
2877 sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
2878 VdbeComment((v, "return address"));
2880 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2883 /* Check to see if this is a vector IN operator */
2884 pLeft = pExpr->pLeft;
2885 nVal = sqlite3ExprVectorSize(pLeft);
2887 /* Construct the ephemeral table that will contain the content of
2888 ** RHS of the IN operator.
2890 pExpr->iTable = iTab;
2891 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
2892 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
2893 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2894 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
2895 }else{
2896 VdbeComment((v, "RHS of IN operator"));
2898 #endif
2899 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
2901 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2902 /* Case 1: expr IN (SELECT ...)
2904 ** Generate code to write the results of the select into the temporary
2905 ** table allocated and opened above.
2907 Select *pSelect = pExpr->x.pSelect;
2908 ExprList *pEList = pSelect->pEList;
2910 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
2911 addrOnce?"":"CORRELATED ", pSelect->selId
2913 /* If the LHS and RHS of the IN operator do not match, that
2914 ** error will have been caught long before we reach this point. */
2915 if( ALWAYS(pEList->nExpr==nVal) ){
2916 SelectDest dest;
2917 int i;
2918 sqlite3SelectDestInit(&dest, SRT_Set, iTab);
2919 dest.zAffSdst = exprINAffinity(pParse, pExpr);
2920 pSelect->iLimit = 0;
2921 testcase( pSelect->selFlags & SF_Distinct );
2922 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2923 if( sqlite3Select(pParse, pSelect, &dest) ){
2924 sqlite3DbFree(pParse->db, dest.zAffSdst);
2925 sqlite3KeyInfoUnref(pKeyInfo);
2926 return;
2928 sqlite3DbFree(pParse->db, dest.zAffSdst);
2929 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2930 assert( pEList!=0 );
2931 assert( pEList->nExpr>0 );
2932 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2933 for(i=0; i<nVal; i++){
2934 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
2935 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2936 pParse, p, pEList->a[i].pExpr
2940 }else if( ALWAYS(pExpr->x.pList!=0) ){
2941 /* Case 2: expr IN (exprlist)
2943 ** For each expression, build an index key from the evaluation and
2944 ** store it in the temporary table. If <expr> is a column, then use
2945 ** that columns affinity when building index keys. If <expr> is not
2946 ** a column, use numeric affinity.
2948 char affinity; /* Affinity of the LHS of the IN */
2949 int i;
2950 ExprList *pList = pExpr->x.pList;
2951 struct ExprList_item *pItem;
2952 int r1, r2;
2953 affinity = sqlite3ExprAffinity(pLeft);
2954 if( affinity<=SQLITE_AFF_NONE ){
2955 affinity = SQLITE_AFF_BLOB;
2956 }else if( affinity==SQLITE_AFF_REAL ){
2957 affinity = SQLITE_AFF_NUMERIC;
2959 if( pKeyInfo ){
2960 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2961 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2964 /* Loop through each expression in <exprlist>. */
2965 r1 = sqlite3GetTempReg(pParse);
2966 r2 = sqlite3GetTempReg(pParse);
2967 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2968 Expr *pE2 = pItem->pExpr;
2970 /* If the expression is not constant then we will need to
2971 ** disable the test that was generated above that makes sure
2972 ** this code only executes once. Because for a non-constant
2973 ** expression we need to rerun this code each time.
2975 if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
2976 sqlite3VdbeChangeToNoop(v, addrOnce);
2977 ExprClearProperty(pExpr, EP_Subrtn);
2978 addrOnce = 0;
2981 /* Evaluate the expression and insert it into the temp table */
2982 sqlite3ExprCode(pParse, pE2, r1);
2983 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
2984 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
2986 sqlite3ReleaseTempReg(pParse, r1);
2987 sqlite3ReleaseTempReg(pParse, r2);
2989 if( pKeyInfo ){
2990 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
2992 if( addrOnce ){
2993 sqlite3VdbeJumpHere(v, addrOnce);
2994 /* Subroutine return */
2995 sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
2996 sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
2997 sqlite3ClearTempRegCache(pParse);
3000 #endif /* SQLITE_OMIT_SUBQUERY */
3003 ** Generate code for scalar subqueries used as a subquery expression
3004 ** or EXISTS operator:
3006 ** (SELECT a FROM b) -- subquery
3007 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3009 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3011 ** Return the register that holds the result. For a multi-column SELECT,
3012 ** the result is stored in a contiguous array of registers and the
3013 ** return value is the register of the left-most result column.
3014 ** Return 0 if an error occurs.
3016 #ifndef SQLITE_OMIT_SUBQUERY
3017 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
3018 int addrOnce = 0; /* Address of OP_Once at top of subroutine */
3019 int rReg = 0; /* Register storing resulting */
3020 Select *pSel; /* SELECT statement to encode */
3021 SelectDest dest; /* How to deal with SELECT result */
3022 int nReg; /* Registers to allocate */
3023 Expr *pLimit; /* New limit expression */
3025 Vdbe *v = pParse->pVdbe;
3026 assert( v!=0 );
3027 testcase( pExpr->op==TK_EXISTS );
3028 testcase( pExpr->op==TK_SELECT );
3029 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
3030 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
3031 pSel = pExpr->x.pSelect;
3033 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3034 ** is encountered if any of the following is true:
3036 ** * The right-hand side is a correlated subquery
3037 ** * The right-hand side is an expression list containing variables
3038 ** * We are inside a trigger
3040 ** If all of the above are false, then we can run this code just once
3041 ** save the results, and reuse the same result on subsequent invocations.
3043 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
3044 /* If this routine has already been coded, then invoke it as a
3045 ** subroutine. */
3046 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3047 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
3048 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3049 pExpr->y.sub.iAddr);
3050 return pExpr->iTable;
3053 /* Begin coding the subroutine */
3054 ExprSetProperty(pExpr, EP_Subrtn);
3055 pExpr->y.sub.regReturn = ++pParse->nMem;
3056 pExpr->y.sub.iAddr =
3057 sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
3058 VdbeComment((v, "return address"));
3060 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3063 /* For a SELECT, generate code to put the values for all columns of
3064 ** the first row into an array of registers and return the index of
3065 ** the first register.
3067 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3068 ** into a register and return that register number.
3070 ** In both cases, the query is augmented with "LIMIT 1". Any
3071 ** preexisting limit is discarded in place of the new LIMIT 1.
3073 ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
3074 addrOnce?"":"CORRELATED ", pSel->selId));
3075 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
3076 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
3077 pParse->nMem += nReg;
3078 if( pExpr->op==TK_SELECT ){
3079 dest.eDest = SRT_Mem;
3080 dest.iSdst = dest.iSDParm;
3081 dest.nSdst = nReg;
3082 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
3083 VdbeComment((v, "Init subquery result"));
3084 }else{
3085 dest.eDest = SRT_Exists;
3086 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
3087 VdbeComment((v, "Init EXISTS result"));
3089 if( pSel->pLimit ){
3090 /* The subquery already has a limit. If the pre-existing limit is X
3091 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3092 sqlite3 *db = pParse->db;
3093 pLimit = sqlite3Expr(db, TK_INTEGER, "0");
3094 if( pLimit ){
3095 pLimit->affExpr = SQLITE_AFF_NUMERIC;
3096 pLimit = sqlite3PExpr(pParse, TK_NE,
3097 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
3099 sqlite3ExprDelete(db, pSel->pLimit->pLeft);
3100 pSel->pLimit->pLeft = pLimit;
3101 }else{
3102 /* If there is no pre-existing limit add a limit of 1 */
3103 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
3104 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
3106 pSel->iLimit = 0;
3107 if( sqlite3Select(pParse, pSel, &dest) ){
3108 return 0;
3110 pExpr->iTable = rReg = dest.iSDParm;
3111 ExprSetVVAProperty(pExpr, EP_NoReduce);
3112 if( addrOnce ){
3113 sqlite3VdbeJumpHere(v, addrOnce);
3115 /* Subroutine return */
3116 sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
3117 sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
3118 sqlite3ClearTempRegCache(pParse);
3121 return rReg;
3123 #endif /* SQLITE_OMIT_SUBQUERY */
3125 #ifndef SQLITE_OMIT_SUBQUERY
3127 ** Expr pIn is an IN(...) expression. This function checks that the
3128 ** sub-select on the RHS of the IN() operator has the same number of
3129 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3130 ** a sub-query, that the LHS is a vector of size 1.
3132 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
3133 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
3134 if( (pIn->flags & EP_xIsSelect) ){
3135 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
3136 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
3137 return 1;
3139 }else if( nVector!=1 ){
3140 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
3141 return 1;
3143 return 0;
3145 #endif
3147 #ifndef SQLITE_OMIT_SUBQUERY
3149 ** Generate code for an IN expression.
3151 ** x IN (SELECT ...)
3152 ** x IN (value, value, ...)
3154 ** The left-hand side (LHS) is a scalar or vector expression. The
3155 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3156 ** subquery. If the RHS is a subquery, the number of result columns must
3157 ** match the number of columns in the vector on the LHS. If the RHS is
3158 ** a list of values, the LHS must be a scalar.
3160 ** The IN operator is true if the LHS value is contained within the RHS.
3161 ** The result is false if the LHS is definitely not in the RHS. The
3162 ** result is NULL if the presence of the LHS in the RHS cannot be
3163 ** determined due to NULLs.
3165 ** This routine generates code that jumps to destIfFalse if the LHS is not
3166 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3167 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3168 ** within the RHS then fall through.
3170 ** See the separate in-operator.md documentation file in the canonical
3171 ** SQLite source tree for additional information.
3173 static void sqlite3ExprCodeIN(
3174 Parse *pParse, /* Parsing and code generating context */
3175 Expr *pExpr, /* The IN expression */
3176 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
3177 int destIfNull /* Jump here if the results are unknown due to NULLs */
3179 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
3180 int eType; /* Type of the RHS */
3181 int rLhs; /* Register(s) holding the LHS values */
3182 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
3183 Vdbe *v; /* Statement under construction */
3184 int *aiMap = 0; /* Map from vector field to index column */
3185 char *zAff = 0; /* Affinity string for comparisons */
3186 int nVector; /* Size of vectors for this IN operator */
3187 int iDummy; /* Dummy parameter to exprCodeVector() */
3188 Expr *pLeft; /* The LHS of the IN operator */
3189 int i; /* loop counter */
3190 int destStep2; /* Where to jump when NULLs seen in step 2 */
3191 int destStep6 = 0; /* Start of code for Step 6 */
3192 int addrTruthOp; /* Address of opcode that determines the IN is true */
3193 int destNotNull; /* Jump here if a comparison is not true in step 6 */
3194 int addrTop; /* Top of the step-6 loop */
3195 int iTab = 0; /* Index to use */
3196 u8 okConstFactor = pParse->okConstFactor;
3198 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3199 pLeft = pExpr->pLeft;
3200 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3201 zAff = exprINAffinity(pParse, pExpr);
3202 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3203 aiMap = (int*)sqlite3DbMallocZero(
3204 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3206 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3208 /* Attempt to compute the RHS. After this step, if anything other than
3209 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3210 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3211 ** the RHS has not yet been coded. */
3212 v = pParse->pVdbe;
3213 assert( v!=0 ); /* OOM detected prior to this routine */
3214 VdbeNoopComment((v, "begin IN expr"));
3215 eType = sqlite3FindInIndex(pParse, pExpr,
3216 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
3217 destIfFalse==destIfNull ? 0 : &rRhsHasNull,
3218 aiMap, &iTab);
3220 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3221 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3223 #ifdef SQLITE_DEBUG
3224 /* Confirm that aiMap[] contains nVector integer values between 0 and
3225 ** nVector-1. */
3226 for(i=0; i<nVector; i++){
3227 int j, cnt;
3228 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3229 assert( cnt==1 );
3231 #endif
3233 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3234 ** vector, then it is stored in an array of nVector registers starting
3235 ** at r1.
3237 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3238 ** so that the fields are in the same order as an existing index. The
3239 ** aiMap[] array contains a mapping from the original LHS field order to
3240 ** the field order that matches the RHS index.
3242 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3243 ** even if it is constant, as OP_Affinity may be used on the register
3244 ** by code generated below. */
3245 assert( pParse->okConstFactor==okConstFactor );
3246 pParse->okConstFactor = 0;
3247 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3248 pParse->okConstFactor = okConstFactor;
3249 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3250 if( i==nVector ){
3251 /* LHS fields are not reordered */
3252 rLhs = rLhsOrig;
3253 }else{
3254 /* Need to reorder the LHS fields according to aiMap */
3255 rLhs = sqlite3GetTempRange(pParse, nVector);
3256 for(i=0; i<nVector; i++){
3257 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3261 /* If sqlite3FindInIndex() did not find or create an index that is
3262 ** suitable for evaluating the IN operator, then evaluate using a
3263 ** sequence of comparisons.
3265 ** This is step (1) in the in-operator.md optimized algorithm.
3267 if( eType==IN_INDEX_NOOP ){
3268 ExprList *pList = pExpr->x.pList;
3269 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3270 int labelOk = sqlite3VdbeMakeLabel(pParse);
3271 int r2, regToFree;
3272 int regCkNull = 0;
3273 int ii;
3274 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3275 if( destIfNull!=destIfFalse ){
3276 regCkNull = sqlite3GetTempReg(pParse);
3277 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
3279 for(ii=0; ii<pList->nExpr; ii++){
3280 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
3281 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
3282 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3284 sqlite3ReleaseTempReg(pParse, regToFree);
3285 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
3286 int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
3287 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
3288 (void*)pColl, P4_COLLSEQ);
3289 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
3290 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
3291 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
3292 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
3293 sqlite3VdbeChangeP5(v, zAff[0]);
3294 }else{
3295 int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
3296 assert( destIfNull==destIfFalse );
3297 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
3298 (void*)pColl, P4_COLLSEQ);
3299 VdbeCoverageIf(v, op==OP_Ne);
3300 VdbeCoverageIf(v, op==OP_IsNull);
3301 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
3304 if( regCkNull ){
3305 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
3306 sqlite3VdbeGoto(v, destIfFalse);
3308 sqlite3VdbeResolveLabel(v, labelOk);
3309 sqlite3ReleaseTempReg(pParse, regCkNull);
3310 goto sqlite3ExprCodeIN_finished;
3313 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3314 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3315 ** We will then skip the binary search of the RHS.
3317 if( destIfNull==destIfFalse ){
3318 destStep2 = destIfFalse;
3319 }else{
3320 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
3322 if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;
3323 for(i=0; i<nVector; i++){
3324 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3325 if( sqlite3ExprCanBeNull(p) ){
3326 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
3327 VdbeCoverage(v);
3331 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3332 ** of the RHS using the LHS as a probe. If found, the result is
3333 ** true.
3335 if( eType==IN_INDEX_ROWID ){
3336 /* In this case, the RHS is the ROWID of table b-tree and so we also
3337 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3338 ** into a single opcode. */
3339 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
3340 VdbeCoverage(v);
3341 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
3342 }else{
3343 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3344 if( destIfFalse==destIfNull ){
3345 /* Combine Step 3 and Step 5 into a single opcode */
3346 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
3347 rLhs, nVector); VdbeCoverage(v);
3348 goto sqlite3ExprCodeIN_finished;
3350 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3351 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
3352 rLhs, nVector); VdbeCoverage(v);
3355 /* Step 4. If the RHS is known to be non-NULL and we did not find
3356 ** an match on the search above, then the result must be FALSE.
3358 if( rRhsHasNull && nVector==1 ){
3359 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3360 VdbeCoverage(v);
3363 /* Step 5. If we do not care about the difference between NULL and
3364 ** FALSE, then just return false.
3366 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3368 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3369 ** If any comparison is NULL, then the result is NULL. If all
3370 ** comparisons are FALSE then the final result is FALSE.
3372 ** For a scalar LHS, it is sufficient to check just the first row
3373 ** of the RHS.
3375 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
3376 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
3377 VdbeCoverage(v);
3378 if( nVector>1 ){
3379 destNotNull = sqlite3VdbeMakeLabel(pParse);
3380 }else{
3381 /* For nVector==1, combine steps 6 and 7 by immediately returning
3382 ** FALSE if the first comparison is not NULL */
3383 destNotNull = destIfFalse;
3385 for(i=0; i<nVector; i++){
3386 Expr *p;
3387 CollSeq *pColl;
3388 int r3 = sqlite3GetTempReg(pParse);
3389 p = sqlite3VectorFieldSubexpr(pLeft, i);
3390 pColl = sqlite3ExprCollSeq(pParse, p);
3391 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
3392 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
3393 (void*)pColl, P4_COLLSEQ);
3394 VdbeCoverage(v);
3395 sqlite3ReleaseTempReg(pParse, r3);
3397 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3398 if( nVector>1 ){
3399 sqlite3VdbeResolveLabel(v, destNotNull);
3400 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
3401 VdbeCoverage(v);
3403 /* Step 7: If we reach this point, we know that the result must
3404 ** be false. */
3405 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3408 /* Jumps here in order to return true. */
3409 sqlite3VdbeJumpHere(v, addrTruthOp);
3411 sqlite3ExprCodeIN_finished:
3412 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
3413 VdbeComment((v, "end IN expr"));
3414 sqlite3ExprCodeIN_oom_error:
3415 sqlite3DbFree(pParse->db, aiMap);
3416 sqlite3DbFree(pParse->db, zAff);
3418 #endif /* SQLITE_OMIT_SUBQUERY */
3420 #ifndef SQLITE_OMIT_FLOATING_POINT
3422 ** Generate an instruction that will put the floating point
3423 ** value described by z[0..n-1] into register iMem.
3425 ** The z[] string will probably not be zero-terminated. But the
3426 ** z[n] character is guaranteed to be something that does not look
3427 ** like the continuation of the number.
3429 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
3430 if( ALWAYS(z!=0) ){
3431 double value;
3432 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
3433 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3434 if( negateFlag ) value = -value;
3435 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
3438 #endif
3442 ** Generate an instruction that will put the integer describe by
3443 ** text z[0..n-1] into register iMem.
3445 ** Expr.u.zToken is always UTF8 and zero-terminated.
3447 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3448 Vdbe *v = pParse->pVdbe;
3449 if( pExpr->flags & EP_IntValue ){
3450 int i = pExpr->u.iValue;
3451 assert( i>=0 );
3452 if( negFlag ) i = -i;
3453 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3454 }else{
3455 int c;
3456 i64 value;
3457 const char *z = pExpr->u.zToken;
3458 assert( z!=0 );
3459 c = sqlite3DecOrHexToI64(z, &value);
3460 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
3461 #ifdef SQLITE_OMIT_FLOATING_POINT
3462 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
3463 #else
3464 #ifndef SQLITE_OMIT_HEX_INTEGER
3465 if( sqlite3_strnicmp(z,"0x",2)==0 ){
3466 sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
3467 }else
3468 #endif
3470 codeReal(v, z, negFlag, iMem);
3472 #endif
3473 }else{
3474 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
3475 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3481 /* Generate code that will load into register regOut a value that is
3482 ** appropriate for the iIdxCol-th column of index pIdx.
3484 void sqlite3ExprCodeLoadIndexColumn(
3485 Parse *pParse, /* The parsing context */
3486 Index *pIdx, /* The index whose column is to be loaded */
3487 int iTabCur, /* Cursor pointing to a table row */
3488 int iIdxCol, /* The column of the index to be loaded */
3489 int regOut /* Store the index column value in this register */
3491 i16 iTabCol = pIdx->aiColumn[iIdxCol];
3492 if( iTabCol==XN_EXPR ){
3493 assert( pIdx->aColExpr );
3494 assert( pIdx->aColExpr->nExpr>iIdxCol );
3495 pParse->iSelfTab = iTabCur + 1;
3496 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
3497 pParse->iSelfTab = 0;
3498 }else{
3499 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3500 iTabCol, regOut);
3504 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3506 ** Generate code that will compute the value of generated column pCol
3507 ** and store the result in register regOut
3509 void sqlite3ExprCodeGeneratedColumn(
3510 Parse *pParse,
3511 Column *pCol,
3512 int regOut
3514 int iAddr;
3515 Vdbe *v = pParse->pVdbe;
3516 assert( v!=0 );
3517 assert( pParse->iSelfTab!=0 );
3518 if( pParse->iSelfTab>0 ){
3519 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
3520 }else{
3521 iAddr = 0;
3523 sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut);
3524 if( pCol->affinity>=SQLITE_AFF_TEXT ){
3525 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
3527 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
3529 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
3532 ** Generate code to extract the value of the iCol-th column of a table.
3534 void sqlite3ExprCodeGetColumnOfTable(
3535 Vdbe *v, /* Parsing context */
3536 Table *pTab, /* The table containing the value */
3537 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
3538 int iCol, /* Index of the column to extract */
3539 int regOut /* Extract the value into this register */
3541 Column *pCol;
3542 assert( v!=0 );
3543 if( pTab==0 ){
3544 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
3545 return;
3547 if( iCol<0 || iCol==pTab->iPKey ){
3548 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3549 }else{
3550 int op;
3551 int x;
3552 if( IsVirtual(pTab) ){
3553 op = OP_VColumn;
3554 x = iCol;
3555 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3556 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
3557 Parse *pParse = sqlite3VdbeParser(v);
3558 if( pCol->colFlags & COLFLAG_BUSY ){
3559 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
3560 }else{
3561 int savedSelfTab = pParse->iSelfTab;
3562 pCol->colFlags |= COLFLAG_BUSY;
3563 pParse->iSelfTab = iTabCur+1;
3564 sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
3565 pParse->iSelfTab = savedSelfTab;
3566 pCol->colFlags &= ~COLFLAG_BUSY;
3568 return;
3569 #endif
3570 }else if( !HasRowid(pTab) ){
3571 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
3572 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3573 op = OP_Column;
3574 }else{
3575 x = sqlite3TableColumnToStorage(pTab,iCol);
3576 testcase( x!=iCol );
3577 op = OP_Column;
3579 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
3580 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3585 ** Generate code that will extract the iColumn-th column from
3586 ** table pTab and store the column value in register iReg.
3588 ** There must be an open cursor to pTab in iTable when this routine
3589 ** is called. If iColumn<0 then code is generated that extracts the rowid.
3591 int sqlite3ExprCodeGetColumn(
3592 Parse *pParse, /* Parsing and code generating context */
3593 Table *pTab, /* Description of the table we are reading from */
3594 int iColumn, /* Index of the table column */
3595 int iTable, /* The cursor pointing to the table */
3596 int iReg, /* Store results here */
3597 u8 p5 /* P5 value for OP_Column + FLAGS */
3599 assert( pParse->pVdbe!=0 );
3600 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
3601 if( p5 ){
3602 VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
3603 if( pOp->opcode==OP_Column ) pOp->p5 = p5;
3605 return iReg;
3609 ** Generate code to move content from registers iFrom...iFrom+nReg-1
3610 ** over to iTo..iTo+nReg-1.
3612 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
3613 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
3617 ** Convert a scalar expression node to a TK_REGISTER referencing
3618 ** register iReg. The caller must ensure that iReg already contains
3619 ** the correct value for the expression.
3621 static void exprToRegister(Expr *pExpr, int iReg){
3622 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
3623 p->op2 = p->op;
3624 p->op = TK_REGISTER;
3625 p->iTable = iReg;
3626 ExprClearProperty(p, EP_Skip);
3630 ** Evaluate an expression (either a vector or a scalar expression) and store
3631 ** the result in continguous temporary registers. Return the index of
3632 ** the first register used to store the result.
3634 ** If the returned result register is a temporary scalar, then also write
3635 ** that register number into *piFreeable. If the returned result register
3636 ** is not a temporary or if the expression is a vector set *piFreeable
3637 ** to 0.
3639 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3640 int iResult;
3641 int nResult = sqlite3ExprVectorSize(p);
3642 if( nResult==1 ){
3643 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3644 }else{
3645 *piFreeable = 0;
3646 if( p->op==TK_SELECT ){
3647 #if SQLITE_OMIT_SUBQUERY
3648 iResult = 0;
3649 #else
3650 iResult = sqlite3CodeSubselect(pParse, p);
3651 #endif
3652 }else{
3653 int i;
3654 iResult = pParse->nMem+1;
3655 pParse->nMem += nResult;
3656 for(i=0; i<nResult; i++){
3657 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
3661 return iResult;
3665 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
3666 ** so that a subsequent copy will not be merged into this one.
3668 static void setDoNotMergeFlagOnCopy(Vdbe *v){
3669 if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){
3670 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergable */
3675 ** Generate code to implement special SQL functions that are implemented
3676 ** in-line rather than by using the usual callbacks.
3678 static int exprCodeInlineFunction(
3679 Parse *pParse, /* Parsing context */
3680 ExprList *pFarg, /* List of function arguments */
3681 int iFuncId, /* Function ID. One of the INTFUNC_... values */
3682 int target /* Store function result in this register */
3684 int nFarg;
3685 Vdbe *v = pParse->pVdbe;
3686 assert( v!=0 );
3687 assert( pFarg!=0 );
3688 nFarg = pFarg->nExpr;
3689 assert( nFarg>0 ); /* All in-line functions have at least one argument */
3690 switch( iFuncId ){
3691 case INLINEFUNC_coalesce: {
3692 /* Attempt a direct implementation of the built-in COALESCE() and
3693 ** IFNULL() functions. This avoids unnecessary evaluation of
3694 ** arguments past the first non-NULL argument.
3696 int endCoalesce = sqlite3VdbeMakeLabel(pParse);
3697 int i;
3698 assert( nFarg>=2 );
3699 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3700 for(i=1; i<nFarg; i++){
3701 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
3702 VdbeCoverage(v);
3703 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
3705 setDoNotMergeFlagOnCopy(v);
3706 sqlite3VdbeResolveLabel(v, endCoalesce);
3707 break;
3709 case INLINEFUNC_iif: {
3710 Expr caseExpr;
3711 memset(&caseExpr, 0, sizeof(caseExpr));
3712 caseExpr.op = TK_CASE;
3713 caseExpr.x.pList = pFarg;
3714 return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
3717 default: {
3718 /* The UNLIKELY() function is a no-op. The result is the value
3719 ** of the first argument.
3721 assert( nFarg==1 || nFarg==2 );
3722 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
3723 break;
3726 /***********************************************************************
3727 ** Test-only SQL functions that are only usable if enabled
3728 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
3730 case INLINEFUNC_expr_compare: {
3731 /* Compare two expressions using sqlite3ExprCompare() */
3732 assert( nFarg==2 );
3733 sqlite3VdbeAddOp2(v, OP_Integer,
3734 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
3735 target);
3736 break;
3739 case INLINEFUNC_expr_implies_expr: {
3740 /* Compare two expressions using sqlite3ExprImpliesExpr() */
3741 assert( nFarg==2 );
3742 sqlite3VdbeAddOp2(v, OP_Integer,
3743 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
3744 target);
3745 break;
3748 case INLINEFUNC_implies_nonnull_row: {
3749 /* REsult of sqlite3ExprImpliesNonNullRow() */
3750 Expr *pA1;
3751 assert( nFarg==2 );
3752 pA1 = pFarg->a[1].pExpr;
3753 if( pA1->op==TK_COLUMN ){
3754 sqlite3VdbeAddOp2(v, OP_Integer,
3755 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),
3756 target);
3757 }else{
3758 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3760 break;
3763 #ifdef SQLITE_DEBUG
3764 case INLINEFUNC_affinity: {
3765 /* The AFFINITY() function evaluates to a string that describes
3766 ** the type affinity of the argument. This is used for testing of
3767 ** the SQLite type logic.
3769 const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
3770 char aff;
3771 assert( nFarg==1 );
3772 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
3773 sqlite3VdbeLoadString(v, target,
3774 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
3775 break;
3777 #endif
3779 return target;
3784 ** Generate code into the current Vdbe to evaluate the given
3785 ** expression. Attempt to store the results in register "target".
3786 ** Return the register where results are stored.
3788 ** With this routine, there is no guarantee that results will
3789 ** be stored in target. The result might be stored in some other
3790 ** register if it is convenient to do so. The calling function
3791 ** must check the return code and move the results to the desired
3792 ** register.
3794 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
3795 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3796 int op; /* The opcode being coded */
3797 int inReg = target; /* Results stored in register inReg */
3798 int regFree1 = 0; /* If non-zero free this temporary register */
3799 int regFree2 = 0; /* If non-zero free this temporary register */
3800 int r1, r2; /* Various register numbers */
3801 Expr tempX; /* Temporary expression node */
3802 int p5 = 0;
3804 assert( target>0 && target<=pParse->nMem );
3805 assert( v!=0 );
3807 expr_code_doover:
3808 if( pExpr==0 ){
3809 op = TK_NULL;
3810 }else{
3811 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3812 op = pExpr->op;
3814 switch( op ){
3815 case TK_AGG_COLUMN: {
3816 AggInfo *pAggInfo = pExpr->pAggInfo;
3817 struct AggInfo_col *pCol;
3818 assert( pAggInfo!=0 );
3819 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
3820 pCol = &pAggInfo->aCol[pExpr->iAgg];
3821 if( !pAggInfo->directMode ){
3822 assert( pCol->iMem>0 );
3823 return pCol->iMem;
3824 }else if( pAggInfo->useSortingIdx ){
3825 Table *pTab = pCol->pTab;
3826 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
3827 pCol->iSorterColumn, target);
3828 if( pCol->iColumn<0 ){
3829 VdbeComment((v,"%s.rowid",pTab->zName));
3830 }else{
3831 VdbeComment((v,"%s.%s",pTab->zName,pTab->aCol[pCol->iColumn].zName));
3832 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
3833 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3836 return target;
3838 /* Otherwise, fall thru into the TK_COLUMN case */
3839 /* no break */ deliberate_fall_through
3841 case TK_COLUMN: {
3842 int iTab = pExpr->iTable;
3843 int iReg;
3844 if( ExprHasProperty(pExpr, EP_FixedCol) ){
3845 /* This COLUMN expression is really a constant due to WHERE clause
3846 ** constraints, and that constant is coded by the pExpr->pLeft
3847 ** expresssion. However, make sure the constant has the correct
3848 ** datatype by applying the Affinity of the table column to the
3849 ** constant.
3851 int aff;
3852 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
3853 if( pExpr->y.pTab ){
3854 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
3855 }else{
3856 aff = pExpr->affExpr;
3858 if( aff>SQLITE_AFF_BLOB ){
3859 static const char zAff[] = "B\000C\000D\000E";
3860 assert( SQLITE_AFF_BLOB=='A' );
3861 assert( SQLITE_AFF_TEXT=='B' );
3862 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
3863 &zAff[(aff-'B')*2], P4_STATIC);
3865 return iReg;
3867 if( iTab<0 ){
3868 if( pParse->iSelfTab<0 ){
3869 /* Other columns in the same row for CHECK constraints or
3870 ** generated columns or for inserting into partial index.
3871 ** The row is unpacked into registers beginning at
3872 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
3873 ** immediately prior to the first column.
3875 Column *pCol;
3876 Table *pTab = pExpr->y.pTab;
3877 int iSrc;
3878 int iCol = pExpr->iColumn;
3879 assert( pTab!=0 );
3880 assert( iCol>=XN_ROWID );
3881 assert( iCol<pTab->nCol );
3882 if( iCol<0 ){
3883 return -1-pParse->iSelfTab;
3885 pCol = pTab->aCol + iCol;
3886 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
3887 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
3888 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3889 if( pCol->colFlags & COLFLAG_GENERATED ){
3890 if( pCol->colFlags & COLFLAG_BUSY ){
3891 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
3892 pCol->zName);
3893 return 0;
3895 pCol->colFlags |= COLFLAG_BUSY;
3896 if( pCol->colFlags & COLFLAG_NOTAVAIL ){
3897 sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
3899 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
3900 return iSrc;
3901 }else
3902 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
3903 if( pCol->affinity==SQLITE_AFF_REAL ){
3904 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
3905 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3906 return target;
3907 }else{
3908 return iSrc;
3910 }else{
3911 /* Coding an expression that is part of an index where column names
3912 ** in the index refer to the table to which the index belongs */
3913 iTab = pParse->iSelfTab - 1;
3916 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
3917 pExpr->iColumn, iTab, target,
3918 pExpr->op2);
3919 if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){
3920 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
3922 return iReg;
3924 case TK_INTEGER: {
3925 codeInteger(pParse, pExpr, 0, target);
3926 return target;
3928 case TK_TRUEFALSE: {
3929 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
3930 return target;
3932 #ifndef SQLITE_OMIT_FLOATING_POINT
3933 case TK_FLOAT: {
3934 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3935 codeReal(v, pExpr->u.zToken, 0, target);
3936 return target;
3938 #endif
3939 case TK_STRING: {
3940 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3941 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
3942 return target;
3944 default: {
3945 /* Make NULL the default case so that if a bug causes an illegal
3946 ** Expr node to be passed into this function, it will be handled
3947 ** sanely and not crash. But keep the assert() to bring the problem
3948 ** to the attention of the developers. */
3949 assert( op==TK_NULL );
3950 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3951 return target;
3953 #ifndef SQLITE_OMIT_BLOB_LITERAL
3954 case TK_BLOB: {
3955 int n;
3956 const char *z;
3957 char *zBlob;
3958 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3959 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3960 assert( pExpr->u.zToken[1]=='\'' );
3961 z = &pExpr->u.zToken[2];
3962 n = sqlite3Strlen30(z) - 1;
3963 assert( z[n]=='\'' );
3964 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3965 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
3966 return target;
3968 #endif
3969 case TK_VARIABLE: {
3970 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3971 assert( pExpr->u.zToken!=0 );
3972 assert( pExpr->u.zToken[0]!=0 );
3973 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3974 if( pExpr->u.zToken[1]!=0 ){
3975 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
3976 assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
3977 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
3978 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
3980 return target;
3982 case TK_REGISTER: {
3983 return pExpr->iTable;
3985 #ifndef SQLITE_OMIT_CAST
3986 case TK_CAST: {
3987 /* Expressions of the form: CAST(pLeft AS token) */
3988 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3989 if( inReg!=target ){
3990 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3991 inReg = target;
3993 sqlite3VdbeAddOp2(v, OP_Cast, target,
3994 sqlite3AffinityType(pExpr->u.zToken, 0));
3995 return inReg;
3997 #endif /* SQLITE_OMIT_CAST */
3998 case TK_IS:
3999 case TK_ISNOT:
4000 op = (op==TK_IS) ? TK_EQ : TK_NE;
4001 p5 = SQLITE_NULLEQ;
4002 /* fall-through */
4003 case TK_LT:
4004 case TK_LE:
4005 case TK_GT:
4006 case TK_GE:
4007 case TK_NE:
4008 case TK_EQ: {
4009 Expr *pLeft = pExpr->pLeft;
4010 if( sqlite3ExprIsVector(pLeft) ){
4011 codeVectorCompare(pParse, pExpr, target, op, p5);
4012 }else{
4013 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
4014 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4015 codeCompare(pParse, pLeft, pExpr->pRight, op,
4016 r1, r2, inReg, SQLITE_STOREP2 | p5,
4017 ExprHasProperty(pExpr,EP_Commuted));
4018 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4019 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4020 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4021 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4022 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
4023 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
4024 testcase( regFree1==0 );
4025 testcase( regFree2==0 );
4027 break;
4029 case TK_AND:
4030 case TK_OR:
4031 case TK_PLUS:
4032 case TK_STAR:
4033 case TK_MINUS:
4034 case TK_REM:
4035 case TK_BITAND:
4036 case TK_BITOR:
4037 case TK_SLASH:
4038 case TK_LSHIFT:
4039 case TK_RSHIFT:
4040 case TK_CONCAT: {
4041 assert( TK_AND==OP_And ); testcase( op==TK_AND );
4042 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
4043 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
4044 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
4045 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
4046 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
4047 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
4048 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
4049 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
4050 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
4051 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
4052 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4053 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4054 sqlite3VdbeAddOp3(v, op, r2, r1, target);
4055 testcase( regFree1==0 );
4056 testcase( regFree2==0 );
4057 break;
4059 case TK_UMINUS: {
4060 Expr *pLeft = pExpr->pLeft;
4061 assert( pLeft );
4062 if( pLeft->op==TK_INTEGER ){
4063 codeInteger(pParse, pLeft, 1, target);
4064 return target;
4065 #ifndef SQLITE_OMIT_FLOATING_POINT
4066 }else if( pLeft->op==TK_FLOAT ){
4067 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4068 codeReal(v, pLeft->u.zToken, 1, target);
4069 return target;
4070 #endif
4071 }else{
4072 tempX.op = TK_INTEGER;
4073 tempX.flags = EP_IntValue|EP_TokenOnly;
4074 tempX.u.iValue = 0;
4075 ExprClearVVAProperties(&tempX);
4076 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
4077 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
4078 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
4079 testcase( regFree2==0 );
4081 break;
4083 case TK_BITNOT:
4084 case TK_NOT: {
4085 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
4086 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
4087 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4088 testcase( regFree1==0 );
4089 sqlite3VdbeAddOp2(v, op, r1, inReg);
4090 break;
4092 case TK_TRUTH: {
4093 int isTrue; /* IS TRUE or IS NOT TRUE */
4094 int bNormal; /* IS TRUE or IS FALSE */
4095 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4096 testcase( regFree1==0 );
4097 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4098 bNormal = pExpr->op2==TK_IS;
4099 testcase( isTrue && bNormal);
4100 testcase( !isTrue && bNormal);
4101 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
4102 break;
4104 case TK_ISNULL:
4105 case TK_NOTNULL: {
4106 int addr;
4107 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4108 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4109 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4110 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4111 testcase( regFree1==0 );
4112 addr = sqlite3VdbeAddOp1(v, op, r1);
4113 VdbeCoverageIf(v, op==TK_ISNULL);
4114 VdbeCoverageIf(v, op==TK_NOTNULL);
4115 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
4116 sqlite3VdbeJumpHere(v, addr);
4117 break;
4119 case TK_AGG_FUNCTION: {
4120 AggInfo *pInfo = pExpr->pAggInfo;
4121 if( pInfo==0
4122 || NEVER(pExpr->iAgg<0)
4123 || NEVER(pExpr->iAgg>=pInfo->nFunc)
4125 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4126 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
4127 }else{
4128 return pInfo->aFunc[pExpr->iAgg].iMem;
4130 break;
4132 case TK_FUNCTION: {
4133 ExprList *pFarg; /* List of function arguments */
4134 int nFarg; /* Number of function arguments */
4135 FuncDef *pDef; /* The function definition object */
4136 const char *zId; /* The function name */
4137 u32 constMask = 0; /* Mask of function arguments that are constant */
4138 int i; /* Loop counter */
4139 sqlite3 *db = pParse->db; /* The database connection */
4140 u8 enc = ENC(db); /* The text encoding used by this database */
4141 CollSeq *pColl = 0; /* A collating sequence */
4143 #ifndef SQLITE_OMIT_WINDOWFUNC
4144 if( ExprHasProperty(pExpr, EP_WinFunc) ){
4145 return pExpr->y.pWin->regResult;
4147 #endif
4149 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
4150 /* SQL functions can be expensive. So try to avoid running them
4151 ** multiple times if we know they always give the same result */
4152 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
4154 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4155 assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
4156 pFarg = pExpr->x.pList;
4157 nFarg = pFarg ? pFarg->nExpr : 0;
4158 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4159 zId = pExpr->u.zToken;
4160 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
4161 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4162 if( pDef==0 && pParse->explain ){
4163 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
4165 #endif
4166 if( pDef==0 || pDef->xFinalize!=0 ){
4167 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
4168 break;
4170 if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
4171 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
4172 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
4173 return exprCodeInlineFunction(pParse, pFarg,
4174 SQLITE_PTR_TO_INT(pDef->pUserData), target);
4175 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
4176 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
4179 for(i=0; i<nFarg; i++){
4180 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
4181 testcase( i==31 );
4182 constMask |= MASKBIT32(i);
4184 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
4185 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
4188 if( pFarg ){
4189 if( constMask ){
4190 r1 = pParse->nMem+1;
4191 pParse->nMem += nFarg;
4192 }else{
4193 r1 = sqlite3GetTempRange(pParse, nFarg);
4196 /* For length() and typeof() functions with a column argument,
4197 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4198 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
4199 ** loading.
4201 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
4202 u8 exprOp;
4203 assert( nFarg==1 );
4204 assert( pFarg->a[0].pExpr!=0 );
4205 exprOp = pFarg->a[0].pExpr->op;
4206 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
4207 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
4208 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
4209 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
4210 pFarg->a[0].pExpr->op2 =
4211 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
4215 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
4216 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
4217 }else{
4218 r1 = 0;
4220 #ifndef SQLITE_OMIT_VIRTUALTABLE
4221 /* Possibly overload the function if the first argument is
4222 ** a virtual table column.
4224 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4225 ** second argument, not the first, as the argument to test to
4226 ** see if it is a column in a virtual table. This is done because
4227 ** the left operand of infix functions (the operand we want to
4228 ** control overloading) ends up as the second argument to the
4229 ** function. The expression "A glob B" is equivalent to
4230 ** "glob(B,A). We want to use the A in "A glob B" to test
4231 ** for function overloading. But we use the B term in "glob(B,A)".
4233 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
4234 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
4235 }else if( nFarg>0 ){
4236 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
4238 #endif
4239 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
4240 if( !pColl ) pColl = db->pDfltColl;
4241 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
4243 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4244 if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
4245 Expr *pArg = pFarg->a[0].pExpr;
4246 if( pArg->op==TK_COLUMN ){
4247 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
4248 }else{
4249 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4251 }else
4252 #endif
4254 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
4255 pDef, pExpr->op2);
4257 if( nFarg ){
4258 if( constMask==0 ){
4259 sqlite3ReleaseTempRange(pParse, r1, nFarg);
4260 }else{
4261 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
4264 return target;
4266 #ifndef SQLITE_OMIT_SUBQUERY
4267 case TK_EXISTS:
4268 case TK_SELECT: {
4269 int nCol;
4270 testcase( op==TK_EXISTS );
4271 testcase( op==TK_SELECT );
4272 if( pParse->db->mallocFailed ){
4273 return 0;
4274 }else if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
4275 sqlite3SubselectError(pParse, nCol, 1);
4276 }else{
4277 return sqlite3CodeSubselect(pParse, pExpr);
4279 break;
4281 case TK_SELECT_COLUMN: {
4282 int n;
4283 if( pExpr->pLeft->iTable==0 ){
4284 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
4286 assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
4287 if( pExpr->iTable!=0
4288 && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
4290 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
4291 pExpr->iTable, n);
4293 return pExpr->pLeft->iTable + pExpr->iColumn;
4295 case TK_IN: {
4296 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4297 int destIfNull = sqlite3VdbeMakeLabel(pParse);
4298 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4299 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4300 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4301 sqlite3VdbeResolveLabel(v, destIfFalse);
4302 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
4303 sqlite3VdbeResolveLabel(v, destIfNull);
4304 return target;
4306 #endif /* SQLITE_OMIT_SUBQUERY */
4310 ** x BETWEEN y AND z
4312 ** This is equivalent to
4314 ** x>=y AND x<=z
4316 ** X is stored in pExpr->pLeft.
4317 ** Y is stored in pExpr->pList->a[0].pExpr.
4318 ** Z is stored in pExpr->pList->a[1].pExpr.
4320 case TK_BETWEEN: {
4321 exprCodeBetween(pParse, pExpr, target, 0, 0);
4322 return target;
4324 case TK_SPAN:
4325 case TK_COLLATE:
4326 case TK_UPLUS: {
4327 pExpr = pExpr->pLeft;
4328 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4331 case TK_TRIGGER: {
4332 /* If the opcode is TK_TRIGGER, then the expression is a reference
4333 ** to a column in the new.* or old.* pseudo-tables available to
4334 ** trigger programs. In this case Expr.iTable is set to 1 for the
4335 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4336 ** is set to the column of the pseudo-table to read, or to -1 to
4337 ** read the rowid field.
4339 ** The expression is implemented using an OP_Param opcode. The p1
4340 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4341 ** to reference another column of the old.* pseudo-table, where
4342 ** i is the index of the column. For a new.rowid reference, p1 is
4343 ** set to (n+1), where n is the number of columns in each pseudo-table.
4344 ** For a reference to any other column in the new.* pseudo-table, p1
4345 ** is set to (n+2+i), where n and i are as defined previously. For
4346 ** example, if the table on which triggers are being fired is
4347 ** declared as:
4349 ** CREATE TABLE t1(a, b);
4351 ** Then p1 is interpreted as follows:
4353 ** p1==0 -> old.rowid p1==3 -> new.rowid
4354 ** p1==1 -> old.a p1==4 -> new.a
4355 ** p1==2 -> old.b p1==5 -> new.b
4357 Table *pTab = pExpr->y.pTab;
4358 int iCol = pExpr->iColumn;
4359 int p1 = pExpr->iTable * (pTab->nCol+1) + 1
4360 + sqlite3TableColumnToStorage(pTab, iCol);
4362 assert( pExpr->iTable==0 || pExpr->iTable==1 );
4363 assert( iCol>=-1 && iCol<pTab->nCol );
4364 assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
4365 assert( p1>=0 && p1<(pTab->nCol*2+2) );
4367 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
4368 VdbeComment((v, "r[%d]=%s.%s", target,
4369 (pExpr->iTable ? "new" : "old"),
4370 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
4373 #ifndef SQLITE_OMIT_FLOATING_POINT
4374 /* If the column has REAL affinity, it may currently be stored as an
4375 ** integer. Use OP_RealAffinity to make sure it is really real.
4377 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
4378 ** floating point when extracting it from the record. */
4379 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
4380 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4382 #endif
4383 break;
4386 case TK_VECTOR: {
4387 sqlite3ErrorMsg(pParse, "row value misused");
4388 break;
4391 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
4392 ** that derive from the right-hand table of a LEFT JOIN. The
4393 ** Expr.iTable value is the table number for the right-hand table.
4394 ** The expression is only evaluated if that table is not currently
4395 ** on a LEFT JOIN NULL row.
4397 case TK_IF_NULL_ROW: {
4398 int addrINR;
4399 u8 okConstFactor = pParse->okConstFactor;
4400 addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
4401 /* Temporarily disable factoring of constant expressions, since
4402 ** even though expressions may appear to be constant, they are not
4403 ** really constant because they originate from the right-hand side
4404 ** of a LEFT JOIN. */
4405 pParse->okConstFactor = 0;
4406 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
4407 pParse->okConstFactor = okConstFactor;
4408 sqlite3VdbeJumpHere(v, addrINR);
4409 sqlite3VdbeChangeP3(v, addrINR, inReg);
4410 break;
4414 ** Form A:
4415 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4417 ** Form B:
4418 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4420 ** Form A is can be transformed into the equivalent form B as follows:
4421 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
4422 ** WHEN x=eN THEN rN ELSE y END
4424 ** X (if it exists) is in pExpr->pLeft.
4425 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
4426 ** odd. The Y is also optional. If the number of elements in x.pList
4427 ** is even, then Y is omitted and the "otherwise" result is NULL.
4428 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
4430 ** The result of the expression is the Ri for the first matching Ei,
4431 ** or if there is no matching Ei, the ELSE term Y, or if there is
4432 ** no ELSE term, NULL.
4434 case TK_CASE: {
4435 int endLabel; /* GOTO label for end of CASE stmt */
4436 int nextCase; /* GOTO label for next WHEN clause */
4437 int nExpr; /* 2x number of WHEN terms */
4438 int i; /* Loop counter */
4439 ExprList *pEList; /* List of WHEN terms */
4440 struct ExprList_item *aListelem; /* Array of WHEN terms */
4441 Expr opCompare; /* The X==Ei expression */
4442 Expr *pX; /* The X expression */
4443 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
4444 Expr *pDel = 0;
4445 sqlite3 *db = pParse->db;
4447 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
4448 assert(pExpr->x.pList->nExpr > 0);
4449 pEList = pExpr->x.pList;
4450 aListelem = pEList->a;
4451 nExpr = pEList->nExpr;
4452 endLabel = sqlite3VdbeMakeLabel(pParse);
4453 if( (pX = pExpr->pLeft)!=0 ){
4454 pDel = sqlite3ExprDup(db, pX, 0);
4455 if( db->mallocFailed ){
4456 sqlite3ExprDelete(db, pDel);
4457 break;
4459 testcase( pX->op==TK_COLUMN );
4460 exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
4461 testcase( regFree1==0 );
4462 memset(&opCompare, 0, sizeof(opCompare));
4463 opCompare.op = TK_EQ;
4464 opCompare.pLeft = pDel;
4465 pTest = &opCompare;
4466 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4467 ** The value in regFree1 might get SCopy-ed into the file result.
4468 ** So make sure that the regFree1 register is not reused for other
4469 ** purposes and possibly overwritten. */
4470 regFree1 = 0;
4472 for(i=0; i<nExpr-1; i=i+2){
4473 if( pX ){
4474 assert( pTest!=0 );
4475 opCompare.pRight = aListelem[i].pExpr;
4476 }else{
4477 pTest = aListelem[i].pExpr;
4479 nextCase = sqlite3VdbeMakeLabel(pParse);
4480 testcase( pTest->op==TK_COLUMN );
4481 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
4482 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
4483 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
4484 sqlite3VdbeGoto(v, endLabel);
4485 sqlite3VdbeResolveLabel(v, nextCase);
4487 if( (nExpr&1)!=0 ){
4488 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
4489 }else{
4490 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4492 sqlite3ExprDelete(db, pDel);
4493 setDoNotMergeFlagOnCopy(v);
4494 sqlite3VdbeResolveLabel(v, endLabel);
4495 break;
4497 #ifndef SQLITE_OMIT_TRIGGER
4498 case TK_RAISE: {
4499 assert( pExpr->affExpr==OE_Rollback
4500 || pExpr->affExpr==OE_Abort
4501 || pExpr->affExpr==OE_Fail
4502 || pExpr->affExpr==OE_Ignore
4504 if( !pParse->pTriggerTab && !pParse->nested ){
4505 sqlite3ErrorMsg(pParse,
4506 "RAISE() may only be used within a trigger-program");
4507 return 0;
4509 if( pExpr->affExpr==OE_Abort ){
4510 sqlite3MayAbort(pParse);
4512 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4513 if( pExpr->affExpr==OE_Ignore ){
4514 sqlite3VdbeAddOp4(
4515 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
4516 VdbeCoverage(v);
4517 }else{
4518 sqlite3HaltConstraint(pParse,
4519 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
4520 pExpr->affExpr, pExpr->u.zToken, 0, 0);
4523 break;
4525 #endif
4527 sqlite3ReleaseTempReg(pParse, regFree1);
4528 sqlite3ReleaseTempReg(pParse, regFree2);
4529 return inReg;
4533 ** Generate code that will evaluate expression pExpr just one time
4534 ** per prepared statement execution.
4536 ** If the expression uses functions (that might throw an exception) then
4537 ** guard them with an OP_Once opcode to ensure that the code is only executed
4538 ** once. If no functions are involved, then factor the code out and put it at
4539 ** the end of the prepared statement in the initialization section.
4541 ** If regDest>=0 then the result is always stored in that register and the
4542 ** result is not reusable. If regDest<0 then this routine is free to
4543 ** store the value whereever it wants. The register where the expression
4544 ** is stored is returned. When regDest<0, two identical expressions might
4545 ** code to the same register, if they do not contain function calls and hence
4546 ** are factored out into the initialization section at the end of the
4547 ** prepared statement.
4549 int sqlite3ExprCodeRunJustOnce(
4550 Parse *pParse, /* Parsing context */
4551 Expr *pExpr, /* The expression to code when the VDBE initializes */
4552 int regDest /* Store the value in this register */
4554 ExprList *p;
4555 assert( ConstFactorOk(pParse) );
4556 p = pParse->pConstExpr;
4557 if( regDest<0 && p ){
4558 struct ExprList_item *pItem;
4559 int i;
4560 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
4561 if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
4562 return pItem->u.iConstExprReg;
4566 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4567 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
4568 Vdbe *v = pParse->pVdbe;
4569 int addr;
4570 assert( v );
4571 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
4572 pParse->okConstFactor = 0;
4573 if( !pParse->db->mallocFailed ){
4574 if( regDest<0 ) regDest = ++pParse->nMem;
4575 sqlite3ExprCode(pParse, pExpr, regDest);
4577 pParse->okConstFactor = 1;
4578 sqlite3ExprDelete(pParse->db, pExpr);
4579 sqlite3VdbeJumpHere(v, addr);
4580 }else{
4581 p = sqlite3ExprListAppend(pParse, p, pExpr);
4582 if( p ){
4583 struct ExprList_item *pItem = &p->a[p->nExpr-1];
4584 pItem->reusable = regDest<0;
4585 if( regDest<0 ) regDest = ++pParse->nMem;
4586 pItem->u.iConstExprReg = regDest;
4588 pParse->pConstExpr = p;
4590 return regDest;
4594 ** Generate code to evaluate an expression and store the results
4595 ** into a register. Return the register number where the results
4596 ** are stored.
4598 ** If the register is a temporary register that can be deallocated,
4599 ** then write its number into *pReg. If the result register is not
4600 ** a temporary, then set *pReg to zero.
4602 ** If pExpr is a constant, then this routine might generate this
4603 ** code to fill the register in the initialization section of the
4604 ** VDBE program, in order to factor it out of the evaluation loop.
4606 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
4607 int r2;
4608 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
4609 if( ConstFactorOk(pParse)
4610 && pExpr->op!=TK_REGISTER
4611 && sqlite3ExprIsConstantNotJoin(pExpr)
4613 *pReg = 0;
4614 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
4615 }else{
4616 int r1 = sqlite3GetTempReg(pParse);
4617 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
4618 if( r2==r1 ){
4619 *pReg = r1;
4620 }else{
4621 sqlite3ReleaseTempReg(pParse, r1);
4622 *pReg = 0;
4625 return r2;
4629 ** Generate code that will evaluate expression pExpr and store the
4630 ** results in register target. The results are guaranteed to appear
4631 ** in register target.
4633 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
4634 int inReg;
4636 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
4637 assert( target>0 && target<=pParse->nMem );
4638 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
4639 if( pParse->pVdbe==0 ) return;
4640 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
4641 if( inReg!=target ){
4642 u8 op;
4643 if( ExprHasProperty(pExpr,EP_Subquery) ){
4644 op = OP_Copy;
4645 }else{
4646 op = OP_SCopy;
4648 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
4653 ** Make a transient copy of expression pExpr and then code it using
4654 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
4655 ** except that the input expression is guaranteed to be unchanged.
4657 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
4658 sqlite3 *db = pParse->db;
4659 pExpr = sqlite3ExprDup(db, pExpr, 0);
4660 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4661 sqlite3ExprDelete(db, pExpr);
4665 ** Generate code that will evaluate expression pExpr and store the
4666 ** results in register target. The results are guaranteed to appear
4667 ** in register target. If the expression is constant, then this routine
4668 ** might choose to code the expression at initialization time.
4670 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4671 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
4672 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
4673 }else{
4674 sqlite3ExprCodeCopy(pParse, pExpr, target);
4679 ** Generate code that pushes the value of every element of the given
4680 ** expression list into a sequence of registers beginning at target.
4682 ** Return the number of elements evaluated. The number returned will
4683 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
4684 ** is defined.
4686 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
4687 ** filled using OP_SCopy. OP_Copy must be used instead.
4689 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4690 ** factored out into initialization code.
4692 ** The SQLITE_ECEL_REF flag means that expressions in the list with
4693 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4694 ** in registers at srcReg, and so the value can be copied from there.
4695 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
4696 ** are simply omitted rather than being copied from srcReg.
4698 int sqlite3ExprCodeExprList(
4699 Parse *pParse, /* Parsing context */
4700 ExprList *pList, /* The expression list to be coded */
4701 int target, /* Where to write results */
4702 int srcReg, /* Source registers if SQLITE_ECEL_REF */
4703 u8 flags /* SQLITE_ECEL_* flags */
4705 struct ExprList_item *pItem;
4706 int i, j, n;
4707 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
4708 Vdbe *v = pParse->pVdbe;
4709 assert( pList!=0 );
4710 assert( target>0 );
4711 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
4712 n = pList->nExpr;
4713 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
4714 for(pItem=pList->a, i=0; i<n; i++, pItem++){
4715 Expr *pExpr = pItem->pExpr;
4716 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
4717 if( pItem->bSorterRef ){
4718 i--;
4719 n--;
4720 }else
4721 #endif
4722 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
4723 if( flags & SQLITE_ECEL_OMITREF ){
4724 i--;
4725 n--;
4726 }else{
4727 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4729 }else if( (flags & SQLITE_ECEL_FACTOR)!=0
4730 && sqlite3ExprIsConstantNotJoin(pExpr)
4732 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
4733 }else{
4734 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4735 if( inReg!=target+i ){
4736 VdbeOp *pOp;
4737 if( copyOp==OP_Copy
4738 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4739 && pOp->p1+pOp->p3+1==inReg
4740 && pOp->p2+pOp->p3+1==target+i
4741 && pOp->p5==0 /* The do-not-merge flag must be clear */
4743 pOp->p3++;
4744 }else{
4745 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4750 return n;
4754 ** Generate code for a BETWEEN operator.
4756 ** x BETWEEN y AND z
4758 ** The above is equivalent to
4760 ** x>=y AND x<=z
4762 ** Code it as such, taking care to do the common subexpression
4763 ** elimination of x.
4765 ** The xJumpIf parameter determines details:
4767 ** NULL: Store the boolean result in reg[dest]
4768 ** sqlite3ExprIfTrue: Jump to dest if true
4769 ** sqlite3ExprIfFalse: Jump to dest if false
4771 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
4773 static void exprCodeBetween(
4774 Parse *pParse, /* Parsing and code generating context */
4775 Expr *pExpr, /* The BETWEEN expression */
4776 int dest, /* Jump destination or storage location */
4777 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
4778 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4780 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
4781 Expr compLeft; /* The x>=y term */
4782 Expr compRight; /* The x<=z term */
4783 int regFree1 = 0; /* Temporary use register */
4784 Expr *pDel = 0;
4785 sqlite3 *db = pParse->db;
4787 memset(&compLeft, 0, sizeof(Expr));
4788 memset(&compRight, 0, sizeof(Expr));
4789 memset(&exprAnd, 0, sizeof(Expr));
4791 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4792 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
4793 if( db->mallocFailed==0 ){
4794 exprAnd.op = TK_AND;
4795 exprAnd.pLeft = &compLeft;
4796 exprAnd.pRight = &compRight;
4797 compLeft.op = TK_GE;
4798 compLeft.pLeft = pDel;
4799 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4800 compRight.op = TK_LE;
4801 compRight.pLeft = pDel;
4802 compRight.pRight = pExpr->x.pList->a[1].pExpr;
4803 exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
4804 if( xJump ){
4805 xJump(pParse, &exprAnd, dest, jumpIfNull);
4806 }else{
4807 /* Mark the expression is being from the ON or USING clause of a join
4808 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
4809 ** it into the Parse.pConstExpr list. We should use a new bit for this,
4810 ** for clarity, but we are out of bits in the Expr.flags field so we
4811 ** have to reuse the EP_FromJoin bit. Bummer. */
4812 pDel->flags |= EP_FromJoin;
4813 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
4815 sqlite3ReleaseTempReg(pParse, regFree1);
4817 sqlite3ExprDelete(db, pDel);
4819 /* Ensure adequate test coverage */
4820 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4821 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4822 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4823 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4824 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4825 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4826 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4827 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
4828 testcase( xJump==0 );
4832 ** Generate code for a boolean expression such that a jump is made
4833 ** to the label "dest" if the expression is true but execution
4834 ** continues straight thru if the expression is false.
4836 ** If the expression evaluates to NULL (neither true nor false), then
4837 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
4839 ** This code depends on the fact that certain token values (ex: TK_EQ)
4840 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4841 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4842 ** the make process cause these values to align. Assert()s in the code
4843 ** below verify that the numbers are aligned correctly.
4845 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4846 Vdbe *v = pParse->pVdbe;
4847 int op = 0;
4848 int regFree1 = 0;
4849 int regFree2 = 0;
4850 int r1, r2;
4852 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4853 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
4854 if( NEVER(pExpr==0) ) return; /* No way this can happen */
4855 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
4856 op = pExpr->op;
4857 switch( op ){
4858 case TK_AND:
4859 case TK_OR: {
4860 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
4861 if( pAlt!=pExpr ){
4862 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
4863 }else if( op==TK_AND ){
4864 int d2 = sqlite3VdbeMakeLabel(pParse);
4865 testcase( jumpIfNull==0 );
4866 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
4867 jumpIfNull^SQLITE_JUMPIFNULL);
4868 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4869 sqlite3VdbeResolveLabel(v, d2);
4870 }else{
4871 testcase( jumpIfNull==0 );
4872 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
4873 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4875 break;
4877 case TK_NOT: {
4878 testcase( jumpIfNull==0 );
4879 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
4880 break;
4882 case TK_TRUTH: {
4883 int isNot; /* IS NOT TRUE or IS NOT FALSE */
4884 int isTrue; /* IS TRUE or IS NOT TRUE */
4885 testcase( jumpIfNull==0 );
4886 isNot = pExpr->op2==TK_ISNOT;
4887 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4888 testcase( isTrue && isNot );
4889 testcase( !isTrue && isNot );
4890 if( isTrue ^ isNot ){
4891 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
4892 isNot ? SQLITE_JUMPIFNULL : 0);
4893 }else{
4894 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
4895 isNot ? SQLITE_JUMPIFNULL : 0);
4897 break;
4899 case TK_IS:
4900 case TK_ISNOT:
4901 testcase( op==TK_IS );
4902 testcase( op==TK_ISNOT );
4903 op = (op==TK_IS) ? TK_EQ : TK_NE;
4904 jumpIfNull = SQLITE_NULLEQ;
4905 /* no break */ deliberate_fall_through
4906 case TK_LT:
4907 case TK_LE:
4908 case TK_GT:
4909 case TK_GE:
4910 case TK_NE:
4911 case TK_EQ: {
4912 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
4913 testcase( jumpIfNull==0 );
4914 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4915 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4916 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
4917 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
4918 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4919 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4920 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4921 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4922 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4923 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4924 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4925 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4926 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4927 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4928 testcase( regFree1==0 );
4929 testcase( regFree2==0 );
4930 break;
4932 case TK_ISNULL:
4933 case TK_NOTNULL: {
4934 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4935 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4936 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4937 sqlite3VdbeAddOp2(v, op, r1, dest);
4938 VdbeCoverageIf(v, op==TK_ISNULL);
4939 VdbeCoverageIf(v, op==TK_NOTNULL);
4940 testcase( regFree1==0 );
4941 break;
4943 case TK_BETWEEN: {
4944 testcase( jumpIfNull==0 );
4945 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
4946 break;
4948 #ifndef SQLITE_OMIT_SUBQUERY
4949 case TK_IN: {
4950 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4951 int destIfNull = jumpIfNull ? dest : destIfFalse;
4952 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4953 sqlite3VdbeGoto(v, dest);
4954 sqlite3VdbeResolveLabel(v, destIfFalse);
4955 break;
4957 #endif
4958 default: {
4959 default_expr:
4960 if( ExprAlwaysTrue(pExpr) ){
4961 sqlite3VdbeGoto(v, dest);
4962 }else if( ExprAlwaysFalse(pExpr) ){
4963 /* No-op */
4964 }else{
4965 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4966 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
4967 VdbeCoverage(v);
4968 testcase( regFree1==0 );
4969 testcase( jumpIfNull==0 );
4971 break;
4974 sqlite3ReleaseTempReg(pParse, regFree1);
4975 sqlite3ReleaseTempReg(pParse, regFree2);
4979 ** Generate code for a boolean expression such that a jump is made
4980 ** to the label "dest" if the expression is false but execution
4981 ** continues straight thru if the expression is true.
4983 ** If the expression evaluates to NULL (neither true nor false) then
4984 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4985 ** is 0.
4987 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4988 Vdbe *v = pParse->pVdbe;
4989 int op = 0;
4990 int regFree1 = 0;
4991 int regFree2 = 0;
4992 int r1, r2;
4994 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4995 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
4996 if( pExpr==0 ) return;
4997 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
4999 /* The value of pExpr->op and op are related as follows:
5001 ** pExpr->op op
5002 ** --------- ----------
5003 ** TK_ISNULL OP_NotNull
5004 ** TK_NOTNULL OP_IsNull
5005 ** TK_NE OP_Eq
5006 ** TK_EQ OP_Ne
5007 ** TK_GT OP_Le
5008 ** TK_LE OP_Gt
5009 ** TK_GE OP_Lt
5010 ** TK_LT OP_Ge
5012 ** For other values of pExpr->op, op is undefined and unused.
5013 ** The value of TK_ and OP_ constants are arranged such that we
5014 ** can compute the mapping above using the following expression.
5015 ** Assert()s verify that the computation is correct.
5017 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
5019 /* Verify correct alignment of TK_ and OP_ constants
5021 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
5022 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
5023 assert( pExpr->op!=TK_NE || op==OP_Eq );
5024 assert( pExpr->op!=TK_EQ || op==OP_Ne );
5025 assert( pExpr->op!=TK_LT || op==OP_Ge );
5026 assert( pExpr->op!=TK_LE || op==OP_Gt );
5027 assert( pExpr->op!=TK_GT || op==OP_Le );
5028 assert( pExpr->op!=TK_GE || op==OP_Lt );
5030 switch( pExpr->op ){
5031 case TK_AND:
5032 case TK_OR: {
5033 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5034 if( pAlt!=pExpr ){
5035 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
5036 }else if( pExpr->op==TK_AND ){
5037 testcase( jumpIfNull==0 );
5038 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5039 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5040 }else{
5041 int d2 = sqlite3VdbeMakeLabel(pParse);
5042 testcase( jumpIfNull==0 );
5043 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
5044 jumpIfNull^SQLITE_JUMPIFNULL);
5045 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5046 sqlite3VdbeResolveLabel(v, d2);
5048 break;
5050 case TK_NOT: {
5051 testcase( jumpIfNull==0 );
5052 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5053 break;
5055 case TK_TRUTH: {
5056 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5057 int isTrue; /* IS TRUE or IS NOT TRUE */
5058 testcase( jumpIfNull==0 );
5059 isNot = pExpr->op2==TK_ISNOT;
5060 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5061 testcase( isTrue && isNot );
5062 testcase( !isTrue && isNot );
5063 if( isTrue ^ isNot ){
5064 /* IS TRUE and IS NOT FALSE */
5065 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5066 isNot ? 0 : SQLITE_JUMPIFNULL);
5068 }else{
5069 /* IS FALSE and IS NOT TRUE */
5070 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5071 isNot ? 0 : SQLITE_JUMPIFNULL);
5073 break;
5075 case TK_IS:
5076 case TK_ISNOT:
5077 testcase( pExpr->op==TK_IS );
5078 testcase( pExpr->op==TK_ISNOT );
5079 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
5080 jumpIfNull = SQLITE_NULLEQ;
5081 /* no break */ deliberate_fall_through
5082 case TK_LT:
5083 case TK_LE:
5084 case TK_GT:
5085 case TK_GE:
5086 case TK_NE:
5087 case TK_EQ: {
5088 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5089 testcase( jumpIfNull==0 );
5090 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5091 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5092 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5093 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
5094 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5095 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5096 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5097 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5098 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5099 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5100 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5101 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5102 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5103 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5104 testcase( regFree1==0 );
5105 testcase( regFree2==0 );
5106 break;
5108 case TK_ISNULL:
5109 case TK_NOTNULL: {
5110 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5111 sqlite3VdbeAddOp2(v, op, r1, dest);
5112 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
5113 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
5114 testcase( regFree1==0 );
5115 break;
5117 case TK_BETWEEN: {
5118 testcase( jumpIfNull==0 );
5119 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
5120 break;
5122 #ifndef SQLITE_OMIT_SUBQUERY
5123 case TK_IN: {
5124 if( jumpIfNull ){
5125 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
5126 }else{
5127 int destIfNull = sqlite3VdbeMakeLabel(pParse);
5128 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
5129 sqlite3VdbeResolveLabel(v, destIfNull);
5131 break;
5133 #endif
5134 default: {
5135 default_expr:
5136 if( ExprAlwaysFalse(pExpr) ){
5137 sqlite3VdbeGoto(v, dest);
5138 }else if( ExprAlwaysTrue(pExpr) ){
5139 /* no-op */
5140 }else{
5141 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5142 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
5143 VdbeCoverage(v);
5144 testcase( regFree1==0 );
5145 testcase( jumpIfNull==0 );
5147 break;
5150 sqlite3ReleaseTempReg(pParse, regFree1);
5151 sqlite3ReleaseTempReg(pParse, regFree2);
5155 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5156 ** code generation, and that copy is deleted after code generation. This
5157 ** ensures that the original pExpr is unchanged.
5159 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
5160 sqlite3 *db = pParse->db;
5161 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
5162 if( db->mallocFailed==0 ){
5163 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
5165 sqlite3ExprDelete(db, pCopy);
5169 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5170 ** type of expression.
5172 ** If pExpr is a simple SQL value - an integer, real, string, blob
5173 ** or NULL value - then the VDBE currently being prepared is configured
5174 ** to re-prepare each time a new value is bound to variable pVar.
5176 ** Additionally, if pExpr is a simple SQL value and the value is the
5177 ** same as that currently bound to variable pVar, non-zero is returned.
5178 ** Otherwise, if the values are not the same or if pExpr is not a simple
5179 ** SQL value, zero is returned.
5181 static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
5182 int res = 0;
5183 int iVar;
5184 sqlite3_value *pL, *pR = 0;
5186 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
5187 if( pR ){
5188 iVar = pVar->iColumn;
5189 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
5190 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
5191 if( pL ){
5192 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
5193 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
5195 res = 0==sqlite3MemCompare(pL, pR, 0);
5197 sqlite3ValueFree(pR);
5198 sqlite3ValueFree(pL);
5201 return res;
5205 ** Do a deep comparison of two expression trees. Return 0 if the two
5206 ** expressions are completely identical. Return 1 if they differ only
5207 ** by a COLLATE operator at the top level. Return 2 if there are differences
5208 ** other than the top-level COLLATE operator.
5210 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5211 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5213 ** The pA side might be using TK_REGISTER. If that is the case and pB is
5214 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5216 ** Sometimes this routine will return 2 even if the two expressions
5217 ** really are equivalent. If we cannot prove that the expressions are
5218 ** identical, we return 2 just to be safe. So if this routine
5219 ** returns 2, then you do not really know for certain if the two
5220 ** expressions are the same. But if you get a 0 or 1 return, then you
5221 ** can be sure the expressions are the same. In the places where
5222 ** this routine is used, it does not hurt to get an extra 2 - that
5223 ** just might result in some slightly slower code. But returning
5224 ** an incorrect 0 or 1 could lead to a malfunction.
5226 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5227 ** pParse->pReprepare can be matched against literals in pB. The
5228 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5229 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5230 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5231 ** pB causes a return value of 2.
5233 int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
5234 u32 combinedFlags;
5235 if( pA==0 || pB==0 ){
5236 return pB==pA ? 0 : 2;
5238 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
5239 return 0;
5241 combinedFlags = pA->flags | pB->flags;
5242 if( combinedFlags & EP_IntValue ){
5243 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
5244 return 0;
5246 return 2;
5248 if( pA->op!=pB->op || pA->op==TK_RAISE ){
5249 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
5250 return 1;
5252 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
5253 return 1;
5255 return 2;
5257 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
5258 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
5259 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5260 #ifndef SQLITE_OMIT_WINDOWFUNC
5261 assert( pA->op==pB->op );
5262 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
5263 return 2;
5265 if( ExprHasProperty(pA,EP_WinFunc) ){
5266 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
5267 return 2;
5270 #endif
5271 }else if( pA->op==TK_NULL ){
5272 return 0;
5273 }else if( pA->op==TK_COLLATE ){
5274 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5275 }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
5276 return 2;
5279 if( (pA->flags & (EP_Distinct|EP_Commuted))
5280 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
5281 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
5282 if( combinedFlags & EP_xIsSelect ) return 2;
5283 if( (combinedFlags & EP_FixedCol)==0
5284 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
5285 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
5286 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
5287 if( pA->op!=TK_STRING
5288 && pA->op!=TK_TRUEFALSE
5289 && ALWAYS((combinedFlags & EP_Reduced)==0)
5291 if( pA->iColumn!=pB->iColumn ) return 2;
5292 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
5293 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
5294 return 2;
5298 return 0;
5302 ** Compare two ExprList objects. Return 0 if they are identical, 1
5303 ** if they are certainly different, or 2 if it is not possible to
5304 ** determine if they are identical or not.
5306 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5307 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5309 ** This routine might return non-zero for equivalent ExprLists. The
5310 ** only consequence will be disabled optimizations. But this routine
5311 ** must never return 0 if the two ExprList objects are different, or
5312 ** a malfunction will result.
5314 ** Two NULL pointers are considered to be the same. But a NULL pointer
5315 ** always differs from a non-NULL pointer.
5317 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
5318 int i;
5319 if( pA==0 && pB==0 ) return 0;
5320 if( pA==0 || pB==0 ) return 1;
5321 if( pA->nExpr!=pB->nExpr ) return 1;
5322 for(i=0; i<pA->nExpr; i++){
5323 int res;
5324 Expr *pExprA = pA->a[i].pExpr;
5325 Expr *pExprB = pB->a[i].pExpr;
5326 if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
5327 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
5329 return 0;
5333 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
5334 ** are ignored.
5336 int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
5337 return sqlite3ExprCompare(0,
5338 sqlite3ExprSkipCollateAndLikely(pA),
5339 sqlite3ExprSkipCollateAndLikely(pB),
5340 iTab);
5344 ** Return non-zero if Expr p can only be true if pNN is not NULL.
5346 ** Or if seenNot is true, return non-zero if Expr p can only be
5347 ** non-NULL if pNN is not NULL
5349 static int exprImpliesNotNull(
5350 Parse *pParse, /* Parsing context */
5351 Expr *p, /* The expression to be checked */
5352 Expr *pNN, /* The expression that is NOT NULL */
5353 int iTab, /* Table being evaluated */
5354 int seenNot /* Return true only if p can be any non-NULL value */
5356 assert( p );
5357 assert( pNN );
5358 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
5359 return pNN->op!=TK_NULL;
5361 switch( p->op ){
5362 case TK_IN: {
5363 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
5364 assert( ExprHasProperty(p,EP_xIsSelect)
5365 || (p->x.pList!=0 && p->x.pList->nExpr>0) );
5366 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5368 case TK_BETWEEN: {
5369 ExprList *pList = p->x.pList;
5370 assert( pList!=0 );
5371 assert( pList->nExpr==2 );
5372 if( seenNot ) return 0;
5373 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
5374 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
5376 return 1;
5378 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5380 case TK_EQ:
5381 case TK_NE:
5382 case TK_LT:
5383 case TK_LE:
5384 case TK_GT:
5385 case TK_GE:
5386 case TK_PLUS:
5387 case TK_MINUS:
5388 case TK_BITOR:
5389 case TK_LSHIFT:
5390 case TK_RSHIFT:
5391 case TK_CONCAT:
5392 seenNot = 1;
5393 /* no break */ deliberate_fall_through
5394 case TK_STAR:
5395 case TK_REM:
5396 case TK_BITAND:
5397 case TK_SLASH: {
5398 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
5399 /* no break */ deliberate_fall_through
5401 case TK_SPAN:
5402 case TK_COLLATE:
5403 case TK_UPLUS:
5404 case TK_UMINUS: {
5405 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
5407 case TK_TRUTH: {
5408 if( seenNot ) return 0;
5409 if( p->op2!=TK_IS ) return 0;
5410 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5412 case TK_BITNOT:
5413 case TK_NOT: {
5414 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5417 return 0;
5421 ** Return true if we can prove the pE2 will always be true if pE1 is
5422 ** true. Return false if we cannot complete the proof or if pE2 might
5423 ** be false. Examples:
5425 ** pE1: x==5 pE2: x==5 Result: true
5426 ** pE1: x>0 pE2: x==5 Result: false
5427 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
5428 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
5429 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
5430 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
5431 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
5433 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
5434 ** Expr.iTable<0 then assume a table number given by iTab.
5436 ** If pParse is not NULL, then the values of bound variables in pE1 are
5437 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
5438 ** modified to record which bound variables are referenced. If pParse
5439 ** is NULL, then false will be returned if pE1 contains any bound variables.
5441 ** When in doubt, return false. Returning true might give a performance
5442 ** improvement. Returning false might cause a performance reduction, but
5443 ** it will always give the correct answer and is hence always safe.
5445 int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
5446 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
5447 return 1;
5449 if( pE2->op==TK_OR
5450 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
5451 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
5453 return 1;
5455 if( pE2->op==TK_NOTNULL
5456 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
5458 return 1;
5460 return 0;
5464 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
5465 ** If the expression node requires that the table at pWalker->iCur
5466 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
5468 ** This routine controls an optimization. False positives (setting
5469 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
5470 ** (never setting pWalker->eCode) is a harmless missed optimization.
5472 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
5473 testcase( pExpr->op==TK_AGG_COLUMN );
5474 testcase( pExpr->op==TK_AGG_FUNCTION );
5475 if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
5476 switch( pExpr->op ){
5477 case TK_ISNOT:
5478 case TK_ISNULL:
5479 case TK_NOTNULL:
5480 case TK_IS:
5481 case TK_OR:
5482 case TK_VECTOR:
5483 case TK_CASE:
5484 case TK_IN:
5485 case TK_FUNCTION:
5486 case TK_TRUTH:
5487 testcase( pExpr->op==TK_ISNOT );
5488 testcase( pExpr->op==TK_ISNULL );
5489 testcase( pExpr->op==TK_NOTNULL );
5490 testcase( pExpr->op==TK_IS );
5491 testcase( pExpr->op==TK_OR );
5492 testcase( pExpr->op==TK_VECTOR );
5493 testcase( pExpr->op==TK_CASE );
5494 testcase( pExpr->op==TK_IN );
5495 testcase( pExpr->op==TK_FUNCTION );
5496 testcase( pExpr->op==TK_TRUTH );
5497 return WRC_Prune;
5498 case TK_COLUMN:
5499 if( pWalker->u.iCur==pExpr->iTable ){
5500 pWalker->eCode = 1;
5501 return WRC_Abort;
5503 return WRC_Prune;
5505 case TK_AND:
5506 if( pWalker->eCode==0 ){
5507 sqlite3WalkExpr(pWalker, pExpr->pLeft);
5508 if( pWalker->eCode ){
5509 pWalker->eCode = 0;
5510 sqlite3WalkExpr(pWalker, pExpr->pRight);
5513 return WRC_Prune;
5515 case TK_BETWEEN:
5516 if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
5517 assert( pWalker->eCode );
5518 return WRC_Abort;
5520 return WRC_Prune;
5522 /* Virtual tables are allowed to use constraints like x=NULL. So
5523 ** a term of the form x=y does not prove that y is not null if x
5524 ** is the column of a virtual table */
5525 case TK_EQ:
5526 case TK_NE:
5527 case TK_LT:
5528 case TK_LE:
5529 case TK_GT:
5530 case TK_GE: {
5531 Expr *pLeft = pExpr->pLeft;
5532 Expr *pRight = pExpr->pRight;
5533 testcase( pExpr->op==TK_EQ );
5534 testcase( pExpr->op==TK_NE );
5535 testcase( pExpr->op==TK_LT );
5536 testcase( pExpr->op==TK_LE );
5537 testcase( pExpr->op==TK_GT );
5538 testcase( pExpr->op==TK_GE );
5539 /* The y.pTab=0 assignment in wherecode.c always happens after the
5540 ** impliesNotNullRow() test */
5541 if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0)
5542 && IsVirtual(pLeft->y.pTab))
5543 || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0)
5544 && IsVirtual(pRight->y.pTab))
5546 return WRC_Prune;
5548 /* no break */ deliberate_fall_through
5550 default:
5551 return WRC_Continue;
5556 ** Return true (non-zero) if expression p can only be true if at least
5557 ** one column of table iTab is non-null. In other words, return true
5558 ** if expression p will always be NULL or false if every column of iTab
5559 ** is NULL.
5561 ** False negatives are acceptable. In other words, it is ok to return
5562 ** zero even if expression p will never be true of every column of iTab
5563 ** is NULL. A false negative is merely a missed optimization opportunity.
5565 ** False positives are not allowed, however. A false positive may result
5566 ** in an incorrect answer.
5568 ** Terms of p that are marked with EP_FromJoin (and hence that come from
5569 ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
5571 ** This routine is used to check if a LEFT JOIN can be converted into
5572 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
5573 ** clause requires that some column of the right table of the LEFT JOIN
5574 ** be non-NULL, then the LEFT JOIN can be safely converted into an
5575 ** ordinary join.
5577 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
5578 Walker w;
5579 p = sqlite3ExprSkipCollateAndLikely(p);
5580 if( p==0 ) return 0;
5581 if( p->op==TK_NOTNULL ){
5582 p = p->pLeft;
5583 }else{
5584 while( p->op==TK_AND ){
5585 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
5586 p = p->pRight;
5589 w.xExprCallback = impliesNotNullRow;
5590 w.xSelectCallback = 0;
5591 w.xSelectCallback2 = 0;
5592 w.eCode = 0;
5593 w.u.iCur = iTab;
5594 sqlite3WalkExpr(&w, p);
5595 return w.eCode;
5599 ** An instance of the following structure is used by the tree walker
5600 ** to determine if an expression can be evaluated by reference to the
5601 ** index only, without having to do a search for the corresponding
5602 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
5603 ** is the cursor for the table.
5605 struct IdxCover {
5606 Index *pIdx; /* The index to be tested for coverage */
5607 int iCur; /* Cursor number for the table corresponding to the index */
5611 ** Check to see if there are references to columns in table
5612 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
5613 ** pWalker->u.pIdxCover->pIdx.
5615 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
5616 if( pExpr->op==TK_COLUMN
5617 && pExpr->iTable==pWalker->u.pIdxCover->iCur
5618 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
5620 pWalker->eCode = 1;
5621 return WRC_Abort;
5623 return WRC_Continue;
5627 ** Determine if an index pIdx on table with cursor iCur contains will
5628 ** the expression pExpr. Return true if the index does cover the
5629 ** expression and false if the pExpr expression references table columns
5630 ** that are not found in the index pIdx.
5632 ** An index covering an expression means that the expression can be
5633 ** evaluated using only the index and without having to lookup the
5634 ** corresponding table entry.
5636 int sqlite3ExprCoveredByIndex(
5637 Expr *pExpr, /* The index to be tested */
5638 int iCur, /* The cursor number for the corresponding table */
5639 Index *pIdx /* The index that might be used for coverage */
5641 Walker w;
5642 struct IdxCover xcov;
5643 memset(&w, 0, sizeof(w));
5644 xcov.iCur = iCur;
5645 xcov.pIdx = pIdx;
5646 w.xExprCallback = exprIdxCover;
5647 w.u.pIdxCover = &xcov;
5648 sqlite3WalkExpr(&w, pExpr);
5649 return !w.eCode;
5654 ** An instance of the following structure is used by the tree walker
5655 ** to count references to table columns in the arguments of an
5656 ** aggregate function, in order to implement the
5657 ** sqlite3FunctionThisSrc() routine.
5659 struct SrcCount {
5660 SrcList *pSrc; /* One particular FROM clause in a nested query */
5661 int iSrcInner; /* Smallest cursor number in this context */
5662 int nThis; /* Number of references to columns in pSrcList */
5663 int nOther; /* Number of references to columns in other FROM clauses */
5667 ** xSelect callback for sqlite3FunctionUsesThisSrc(). If this is the first
5668 ** SELECT with a FROM clause encountered during this iteration, set
5669 ** SrcCount.iSrcInner to the cursor number of the leftmost object in
5670 ** the FROM cause.
5672 static int selectSrcCount(Walker *pWalker, Select *pSel){
5673 struct SrcCount *p = pWalker->u.pSrcCount;
5674 if( p->iSrcInner==0x7FFFFFFF && ALWAYS(pSel->pSrc) && pSel->pSrc->nSrc ){
5675 pWalker->u.pSrcCount->iSrcInner = pSel->pSrc->a[0].iCursor;
5677 return WRC_Continue;
5681 ** Count the number of references to columns.
5683 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
5684 /* There was once a NEVER() on the second term on the grounds that
5685 ** sqlite3FunctionUsesThisSrc() was always called before
5686 ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet
5687 ** been converted into TK_AGG_COLUMN. But this is no longer true due
5688 ** to window functions - sqlite3WindowRewrite() may now indirectly call
5689 ** FunctionUsesThisSrc() when creating a new sub-select. */
5690 if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
5691 int i;
5692 struct SrcCount *p = pWalker->u.pSrcCount;
5693 SrcList *pSrc = p->pSrc;
5694 int nSrc = pSrc ? pSrc->nSrc : 0;
5695 for(i=0; i<nSrc; i++){
5696 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
5698 if( i<nSrc ){
5699 p->nThis++;
5700 }else if( pExpr->iTable<p->iSrcInner ){
5701 /* In a well-formed parse tree (no name resolution errors),
5702 ** TK_COLUMN nodes with smaller Expr.iTable values are in an
5703 ** outer context. Those are the only ones to count as "other" */
5704 p->nOther++;
5707 return WRC_Continue;
5711 ** Determine if any of the arguments to the pExpr Function reference
5712 ** pSrcList. Return true if they do. Also return true if the function
5713 ** has no arguments or has only constant arguments. Return false if pExpr
5714 ** references columns but not columns of tables found in pSrcList.
5716 int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
5717 Walker w;
5718 struct SrcCount cnt;
5719 assert( pExpr->op==TK_AGG_FUNCTION );
5720 memset(&w, 0, sizeof(w));
5721 w.xExprCallback = exprSrcCount;
5722 w.xSelectCallback = selectSrcCount;
5723 w.u.pSrcCount = &cnt;
5724 cnt.pSrc = pSrcList;
5725 cnt.iSrcInner = (pSrcList&&pSrcList->nSrc)?pSrcList->a[0].iCursor:0x7FFFFFFF;
5726 cnt.nThis = 0;
5727 cnt.nOther = 0;
5728 sqlite3WalkExprList(&w, pExpr->x.pList);
5729 #ifndef SQLITE_OMIT_WINDOWFUNC
5730 if( ExprHasProperty(pExpr, EP_WinFunc) ){
5731 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
5733 #endif
5734 return cnt.nThis>0 || cnt.nOther==0;
5738 ** This is a Walker expression node callback.
5740 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
5741 ** object that is referenced does not refer directly to the Expr. If
5742 ** it does, make a copy. This is done because the pExpr argument is
5743 ** subject to change.
5745 ** The copy is stored on pParse->pConstExpr with a register number of 0.
5746 ** This will cause the expression to be deleted automatically when the
5747 ** Parse object is destroyed, but the zero register number means that it
5748 ** will not generate any code in the preamble.
5750 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
5751 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
5752 && pExpr->pAggInfo!=0
5754 AggInfo *pAggInfo = pExpr->pAggInfo;
5755 int iAgg = pExpr->iAgg;
5756 Parse *pParse = pWalker->pParse;
5757 sqlite3 *db = pParse->db;
5758 assert( pExpr->op==TK_AGG_COLUMN || pExpr->op==TK_AGG_FUNCTION );
5759 if( pExpr->op==TK_AGG_COLUMN ){
5760 assert( iAgg>=0 && iAgg<pAggInfo->nColumn );
5761 if( pAggInfo->aCol[iAgg].pCExpr==pExpr ){
5762 pExpr = sqlite3ExprDup(db, pExpr, 0);
5763 if( pExpr ){
5764 pAggInfo->aCol[iAgg].pCExpr = pExpr;
5765 pParse->pConstExpr =
5766 sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
5769 }else{
5770 assert( iAgg>=0 && iAgg<pAggInfo->nFunc );
5771 if( pAggInfo->aFunc[iAgg].pFExpr==pExpr ){
5772 pExpr = sqlite3ExprDup(db, pExpr, 0);
5773 if( pExpr ){
5774 pAggInfo->aFunc[iAgg].pFExpr = pExpr;
5775 pParse->pConstExpr =
5776 sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr);
5781 return WRC_Continue;
5785 ** Initialize a Walker object so that will persist AggInfo entries referenced
5786 ** by the tree that is walked.
5788 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
5789 memset(pWalker, 0, sizeof(*pWalker));
5790 pWalker->pParse = pParse;
5791 pWalker->xExprCallback = agginfoPersistExprCb;
5792 pWalker->xSelectCallback = sqlite3SelectWalkNoop;
5796 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
5797 ** the new element. Return a negative number if malloc fails.
5799 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
5800 int i;
5801 pInfo->aCol = sqlite3ArrayAllocate(
5803 pInfo->aCol,
5804 sizeof(pInfo->aCol[0]),
5805 &pInfo->nColumn,
5808 return i;
5812 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
5813 ** the new element. Return a negative number if malloc fails.
5815 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
5816 int i;
5817 pInfo->aFunc = sqlite3ArrayAllocate(
5818 db,
5819 pInfo->aFunc,
5820 sizeof(pInfo->aFunc[0]),
5821 &pInfo->nFunc,
5824 return i;
5828 ** This is the xExprCallback for a tree walker. It is used to
5829 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
5830 ** for additional information.
5832 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
5833 int i;
5834 NameContext *pNC = pWalker->u.pNC;
5835 Parse *pParse = pNC->pParse;
5836 SrcList *pSrcList = pNC->pSrcList;
5837 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
5839 assert( pNC->ncFlags & NC_UAggInfo );
5840 switch( pExpr->op ){
5841 case TK_AGG_COLUMN:
5842 case TK_COLUMN: {
5843 testcase( pExpr->op==TK_AGG_COLUMN );
5844 testcase( pExpr->op==TK_COLUMN );
5845 /* Check to see if the column is in one of the tables in the FROM
5846 ** clause of the aggregate query */
5847 if( ALWAYS(pSrcList!=0) ){
5848 struct SrcList_item *pItem = pSrcList->a;
5849 for(i=0; i<pSrcList->nSrc; i++, pItem++){
5850 struct AggInfo_col *pCol;
5851 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
5852 if( pExpr->iTable==pItem->iCursor ){
5853 /* If we reach this point, it means that pExpr refers to a table
5854 ** that is in the FROM clause of the aggregate query.
5856 ** Make an entry for the column in pAggInfo->aCol[] if there
5857 ** is not an entry there already.
5859 int k;
5860 pCol = pAggInfo->aCol;
5861 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
5862 if( pCol->iTable==pExpr->iTable &&
5863 pCol->iColumn==pExpr->iColumn ){
5864 break;
5867 if( (k>=pAggInfo->nColumn)
5868 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
5870 pCol = &pAggInfo->aCol[k];
5871 pCol->pTab = pExpr->y.pTab;
5872 pCol->iTable = pExpr->iTable;
5873 pCol->iColumn = pExpr->iColumn;
5874 pCol->iMem = ++pParse->nMem;
5875 pCol->iSorterColumn = -1;
5876 pCol->pCExpr = pExpr;
5877 if( pAggInfo->pGroupBy ){
5878 int j, n;
5879 ExprList *pGB = pAggInfo->pGroupBy;
5880 struct ExprList_item *pTerm = pGB->a;
5881 n = pGB->nExpr;
5882 for(j=0; j<n; j++, pTerm++){
5883 Expr *pE = pTerm->pExpr;
5884 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
5885 pE->iColumn==pExpr->iColumn ){
5886 pCol->iSorterColumn = j;
5887 break;
5891 if( pCol->iSorterColumn<0 ){
5892 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
5895 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
5896 ** because it was there before or because we just created it).
5897 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
5898 ** pAggInfo->aCol[] entry.
5900 ExprSetVVAProperty(pExpr, EP_NoReduce);
5901 pExpr->pAggInfo = pAggInfo;
5902 pExpr->op = TK_AGG_COLUMN;
5903 pExpr->iAgg = (i16)k;
5904 break;
5905 } /* endif pExpr->iTable==pItem->iCursor */
5906 } /* end loop over pSrcList */
5908 return WRC_Prune;
5910 case TK_AGG_FUNCTION: {
5911 if( (pNC->ncFlags & NC_InAggFunc)==0
5912 && pWalker->walkerDepth==pExpr->op2
5914 /* Check to see if pExpr is a duplicate of another aggregate
5915 ** function that is already in the pAggInfo structure
5917 struct AggInfo_func *pItem = pAggInfo->aFunc;
5918 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
5919 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
5920 break;
5923 if( i>=pAggInfo->nFunc ){
5924 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
5926 u8 enc = ENC(pParse->db);
5927 i = addAggInfoFunc(pParse->db, pAggInfo);
5928 if( i>=0 ){
5929 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
5930 pItem = &pAggInfo->aFunc[i];
5931 pItem->pFExpr = pExpr;
5932 pItem->iMem = ++pParse->nMem;
5933 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5934 pItem->pFunc = sqlite3FindFunction(pParse->db,
5935 pExpr->u.zToken,
5936 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
5937 if( pExpr->flags & EP_Distinct ){
5938 pItem->iDistinct = pParse->nTab++;
5939 }else{
5940 pItem->iDistinct = -1;
5944 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
5946 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
5947 ExprSetVVAProperty(pExpr, EP_NoReduce);
5948 pExpr->iAgg = (i16)i;
5949 pExpr->pAggInfo = pAggInfo;
5950 return WRC_Prune;
5951 }else{
5952 return WRC_Continue;
5956 return WRC_Continue;
5960 ** Analyze the pExpr expression looking for aggregate functions and
5961 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
5962 ** points to. Additional entries are made on the AggInfo object as
5963 ** necessary.
5965 ** This routine should only be called after the expression has been
5966 ** analyzed by sqlite3ResolveExprNames().
5968 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
5969 Walker w;
5970 w.xExprCallback = analyzeAggregate;
5971 w.xSelectCallback = sqlite3WalkerDepthIncrease;
5972 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
5973 w.walkerDepth = 0;
5974 w.u.pNC = pNC;
5975 w.pParse = 0;
5976 assert( pNC->pSrcList!=0 );
5977 sqlite3WalkExpr(&w, pExpr);
5981 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
5982 ** expression list. Return the number of errors.
5984 ** If an error is found, the analysis is cut short.
5986 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
5987 struct ExprList_item *pItem;
5988 int i;
5989 if( pList ){
5990 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
5991 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
5997 ** Allocate a single new register for use to hold some intermediate result.
5999 int sqlite3GetTempReg(Parse *pParse){
6000 if( pParse->nTempReg==0 ){
6001 return ++pParse->nMem;
6003 return pParse->aTempReg[--pParse->nTempReg];
6007 ** Deallocate a register, making available for reuse for some other
6008 ** purpose.
6010 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
6011 if( iReg ){
6012 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
6013 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
6014 pParse->aTempReg[pParse->nTempReg++] = iReg;
6020 ** Allocate or deallocate a block of nReg consecutive registers.
6022 int sqlite3GetTempRange(Parse *pParse, int nReg){
6023 int i, n;
6024 if( nReg==1 ) return sqlite3GetTempReg(pParse);
6025 i = pParse->iRangeReg;
6026 n = pParse->nRangeReg;
6027 if( nReg<=n ){
6028 pParse->iRangeReg += nReg;
6029 pParse->nRangeReg -= nReg;
6030 }else{
6031 i = pParse->nMem+1;
6032 pParse->nMem += nReg;
6034 return i;
6036 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
6037 if( nReg==1 ){
6038 sqlite3ReleaseTempReg(pParse, iReg);
6039 return;
6041 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
6042 if( nReg>pParse->nRangeReg ){
6043 pParse->nRangeReg = nReg;
6044 pParse->iRangeReg = iReg;
6049 ** Mark all temporary registers as being unavailable for reuse.
6051 ** Always invoke this procedure after coding a subroutine or co-routine
6052 ** that might be invoked from other parts of the code, to ensure that
6053 ** the sub/co-routine does not use registers in common with the code that
6054 ** invokes the sub/co-routine.
6056 void sqlite3ClearTempRegCache(Parse *pParse){
6057 pParse->nTempReg = 0;
6058 pParse->nRangeReg = 0;
6062 ** Validate that no temporary register falls within the range of
6063 ** iFirst..iLast, inclusive. This routine is only call from within assert()
6064 ** statements.
6066 #ifdef SQLITE_DEBUG
6067 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
6068 int i;
6069 if( pParse->nRangeReg>0
6070 && pParse->iRangeReg+pParse->nRangeReg > iFirst
6071 && pParse->iRangeReg <= iLast
6073 return 0;
6075 for(i=0; i<pParse->nTempReg; i++){
6076 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
6077 return 0;
6080 return 1;
6082 #endif /* SQLITE_DEBUG */