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. 10 ** 11 ************************************************************************* 12 ** This file contains routines used for analyzing expressions and 13 ** for generating VDBE code that evaluates expressions in SQLite. 14 */ 15 #include "sqliteInt.h" 16 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); 20 21 /* 22 ** Return the affinity character for a single column of a table. 23 */ 24 char sqlite3TableColumnAffinity(Table *pTab, int iCol){ 25 assert( iCol<pTab->nCol ); 26 return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER; 27 } 28 29 /* 30 ** Return the 'affinity' of the expression pExpr if any. 31 ** 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. 36 ** 37 ** i.e. the WHERE clause expressions in the following statements all 38 ** have an affinity: 39 ** 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); 44 */ 45 char sqlite3ExprAffinity(Expr *pExpr){ 46 int op; 47 if( pExpr->flags & EP_Generic ) return 0; 48 while( ExprHasProperty(pExpr, EP_Skip) ){ 49 assert( pExpr->op==TK_COLLATE ); 50 pExpr = pExpr->pLeft; 51 assert( pExpr!=0 ); 52 } 53 op = pExpr->op; 54 if( op==TK_SELECT ){ 55 assert( pExpr->flags&EP_xIsSelect ); 56 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); 57 } 58 if( op==TK_REGISTER ) op = pExpr->op2; 59 #ifndef SQLITE_OMIT_CAST 60 if( op==TK_CAST ){ 61 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 62 return sqlite3AffinityType(pExpr->u.zToken, 0); 63 } 64 #endif 65 if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){ 66 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); 67 } 68 if( op==TK_SELECT_COLUMN ){ 69 assert( pExpr->pLeft->flags&EP_xIsSelect ); 70 return sqlite3ExprAffinity( 71 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr 72 ); 73 } 74 return pExpr->affinity; 75 } 76 77 /* 78 ** Set the collating sequence for expression pExpr to be the collating 79 ** sequence named by pToken. Return a pointer to a new Expr node that 80 ** implements the COLLATE operator. 81 ** 82 ** If a memory allocation error occurs, that fact is recorded in pParse->db 83 ** and the pExpr parameter is returned unchanged. 84 */ 85 Expr *sqlite3ExprAddCollateToken( 86 Parse *pParse, /* Parsing context */ 87 Expr *pExpr, /* Add the "COLLATE" clause to this expression */ 88 const Token *pCollName, /* Name of collating sequence */ 89 int dequote /* True to dequote pCollName */ 90 ){ 91 if( pCollName->n>0 ){ 92 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); 93 if( pNew ){ 94 pNew->pLeft = pExpr; 95 pNew->flags |= EP_Collate|EP_Skip; 96 pExpr = pNew; 97 } 98 } 99 return pExpr; 100 } 101 Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ 102 Token s; 103 assert( zC!=0 ); 104 sqlite3TokenInit(&s, (char*)zC); 105 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); 106 } 107 108 /* 109 ** Skip over any TK_COLLATE operators and any unlikely() 110 ** or likelihood() function at the root of an expression. 111 */ 112 Expr *sqlite3ExprSkipCollate(Expr *pExpr){ 113 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){ 114 if( ExprHasProperty(pExpr, EP_Unlikely) ){ 115 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 116 assert( pExpr->x.pList->nExpr>0 ); 117 assert( pExpr->op==TK_FUNCTION ); 118 pExpr = pExpr->x.pList->a[0].pExpr; 119 }else{ 120 assert( pExpr->op==TK_COLLATE ); 121 pExpr = pExpr->pLeft; 122 } 123 } 124 return pExpr; 125 } 126 127 /* 128 ** Return the collation sequence for the expression pExpr. If 129 ** there is no defined collating sequence, return NULL. 130 ** 131 ** See also: sqlite3ExprNNCollSeq() 132 ** 133 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the 134 ** default collation if pExpr has no defined collation. 135 ** 136 ** The collating sequence might be determined by a COLLATE operator 137 ** or by the presence of a column with a defined collating sequence. 138 ** COLLATE operators take first precedence. Left operands take 139 ** precedence over right operands. 140 */ 141 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ 142 sqlite3 *db = pParse->db; 143 CollSeq *pColl = 0; 144 Expr *p = pExpr; 145 while( p ){ 146 int op = p->op; 147 if( p->flags & EP_Generic ) break; 148 if( op==TK_REGISTER ) op = p->op2; 149 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER) 150 && p->y.pTab!=0 151 ){ 152 /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally 153 ** a TK_COLUMN but was previously evaluated and cached in a register */ 154 int j = p->iColumn; 155 if( j>=0 ){ 156 const char *zColl = p->y.pTab->aCol[j].zColl; 157 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 158 } 159 break; 160 } 161 if( op==TK_CAST || op==TK_UPLUS ){ 162 p = p->pLeft; 163 continue; 164 } 165 if( op==TK_COLLATE ){ 166 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); 167 break; 168 } 169 if( p->flags & EP_Collate ){ 170 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){ 171 p = p->pLeft; 172 }else{ 173 Expr *pNext = p->pRight; 174 /* The Expr.x union is never used at the same time as Expr.pRight */ 175 assert( p->x.pList==0 || p->pRight==0 ); 176 /* p->flags holds EP_Collate and p->pLeft->flags does not. And 177 ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at 178 ** least one EP_Collate. Thus the following two ALWAYS. */ 179 if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){ 180 int i; 181 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){ 182 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){ 183 pNext = p->x.pList->a[i].pExpr; 184 break; 185 } 186 } 187 } 188 p = pNext; 189 } 190 }else{ 191 break; 192 } 193 } 194 if( sqlite3CheckCollSeq(pParse, pColl) ){ 195 pColl = 0; 196 } 197 return pColl; 198 } 199 200 /* 201 ** Return the collation sequence for the expression pExpr. If 202 ** there is no defined collating sequence, return a pointer to the 203 ** defautl collation sequence. 204 ** 205 ** See also: sqlite3ExprCollSeq() 206 ** 207 ** The sqlite3ExprCollSeq() routine works the same except that it 208 ** returns NULL if there is no defined collation. 209 */ 210 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){ 211 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr); 212 if( p==0 ) p = pParse->db->pDfltColl; 213 assert( p!=0 ); 214 return p; 215 } 216 217 /* 218 ** Return TRUE if the two expressions have equivalent collating sequences. 219 */ 220 int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){ 221 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1); 222 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2); 223 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0; 224 } 225 226 /* 227 ** pExpr is an operand of a comparison operator. aff2 is the 228 ** type affinity of the other operand. This routine returns the 229 ** type affinity that should be used for the comparison operator. 230 */ 231 char sqlite3CompareAffinity(Expr *pExpr, char aff2){ 232 char aff1 = sqlite3ExprAffinity(pExpr); 233 if( aff1 && aff2 ){ 234 /* Both sides of the comparison are columns. If one has numeric 235 ** affinity, use that. Otherwise use no affinity. 236 */ 237 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ 238 return SQLITE_AFF_NUMERIC; 239 }else{ 240 return SQLITE_AFF_BLOB; 241 } 242 }else if( !aff1 && !aff2 ){ 243 /* Neither side of the comparison is a column. Compare the 244 ** results directly. 245 */ 246 return SQLITE_AFF_BLOB; 247 }else{ 248 /* One side is a column, the other is not. Use the columns affinity. */ 249 assert( aff1==0 || aff2==0 ); 250 return (aff1 + aff2); 251 } 252 } 253 254 /* 255 ** pExpr is a comparison operator. Return the type affinity that should 256 ** be applied to both operands prior to doing the comparison. 257 */ 258 static char comparisonAffinity(Expr *pExpr){ 259 char aff; 260 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || 261 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || 262 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); 263 assert( pExpr->pLeft ); 264 aff = sqlite3ExprAffinity(pExpr->pLeft); 265 if( pExpr->pRight ){ 266 aff = sqlite3CompareAffinity(pExpr->pRight, aff); 267 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 268 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); 269 }else if( aff==0 ){ 270 aff = SQLITE_AFF_BLOB; 271 } 272 return aff; 273 } 274 275 /* 276 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. 277 ** idx_affinity is the affinity of an indexed column. Return true 278 ** if the index with affinity idx_affinity may be used to implement 279 ** the comparison in pExpr. 280 */ 281 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ 282 char aff = comparisonAffinity(pExpr); 283 switch( aff ){ 284 case SQLITE_AFF_BLOB: 285 return 1; 286 case SQLITE_AFF_TEXT: 287 return idx_affinity==SQLITE_AFF_TEXT; 288 default: 289 return sqlite3IsNumericAffinity(idx_affinity); 290 } 291 } 292 293 /* 294 ** Return the P5 value that should be used for a binary comparison 295 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. 296 */ 297 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ 298 u8 aff = (char)sqlite3ExprAffinity(pExpr2); 299 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; 300 return aff; 301 } 302 303 /* 304 ** Return a pointer to the collation sequence that should be used by 305 ** a binary comparison operator comparing pLeft and pRight. 306 ** 307 ** If the left hand expression has a collating sequence type, then it is 308 ** used. Otherwise the collation sequence for the right hand expression 309 ** is used, or the default (BINARY) if neither expression has a collating 310 ** type. 311 ** 312 ** Argument pRight (but not pLeft) may be a null pointer. In this case, 313 ** it is not considered. 314 */ 315 CollSeq *sqlite3BinaryCompareCollSeq( 316 Parse *pParse, 317 Expr *pLeft, 318 Expr *pRight 319 ){ 320 CollSeq *pColl; 321 assert( pLeft ); 322 if( pLeft->flags & EP_Collate ){ 323 pColl = sqlite3ExprCollSeq(pParse, pLeft); 324 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ 325 pColl = sqlite3ExprCollSeq(pParse, pRight); 326 }else{ 327 pColl = sqlite3ExprCollSeq(pParse, pLeft); 328 if( !pColl ){ 329 pColl = sqlite3ExprCollSeq(pParse, pRight); 330 } 331 } 332 return pColl; 333 } 334 335 /* 336 ** Generate code for a comparison operator. 337 */ 338 static int codeCompare( 339 Parse *pParse, /* The parsing (and code generating) context */ 340 Expr *pLeft, /* The left operand */ 341 Expr *pRight, /* The right operand */ 342 int opcode, /* The comparison opcode */ 343 int in1, int in2, /* Register holding operands */ 344 int dest, /* Jump here if true. */ 345 int jumpIfNull /* If true, jump if either operand is NULL */ 346 ){ 347 int p5; 348 int addr; 349 CollSeq *p4; 350 351 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); 352 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); 353 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, 354 (void*)p4, P4_COLLSEQ); 355 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); 356 return addr; 357 } 358 359 /* 360 ** Return true if expression pExpr is a vector, or false otherwise. 361 ** 362 ** A vector is defined as any expression that results in two or more 363 ** columns of result. Every TK_VECTOR node is an vector because the 364 ** parser will not generate a TK_VECTOR with fewer than two entries. 365 ** But a TK_SELECT might be either a vector or a scalar. It is only 366 ** considered a vector if it has two or more result columns. 367 */ 368 int sqlite3ExprIsVector(Expr *pExpr){ 369 return sqlite3ExprVectorSize(pExpr)>1; 370 } 371 372 /* 373 ** If the expression passed as the only argument is of type TK_VECTOR 374 ** return the number of expressions in the vector. Or, if the expression 375 ** is a sub-select, return the number of columns in the sub-select. For 376 ** any other type of expression, return 1. 377 */ 378 int sqlite3ExprVectorSize(Expr *pExpr){ 379 u8 op = pExpr->op; 380 if( op==TK_REGISTER ) op = pExpr->op2; 381 if( op==TK_VECTOR ){ 382 return pExpr->x.pList->nExpr; 383 }else if( op==TK_SELECT ){ 384 return pExpr->x.pSelect->pEList->nExpr; 385 }else{ 386 return 1; 387 } 388 } 389 390 /* 391 ** Return a pointer to a subexpression of pVector that is the i-th 392 ** column of the vector (numbered starting with 0). The caller must 393 ** ensure that i is within range. 394 ** 395 ** If pVector is really a scalar (and "scalar" here includes subqueries 396 ** that return a single column!) then return pVector unmodified. 397 ** 398 ** pVector retains ownership of the returned subexpression. 399 ** 400 ** If the vector is a (SELECT ...) then the expression returned is 401 ** just the expression for the i-th term of the result set, and may 402 ** not be ready for evaluation because the table cursor has not yet 403 ** been positioned. 404 */ 405 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ 406 assert( i<sqlite3ExprVectorSize(pVector) ); 407 if( sqlite3ExprIsVector(pVector) ){ 408 assert( pVector->op2==0 || pVector->op==TK_REGISTER ); 409 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){ 410 return pVector->x.pSelect->pEList->a[i].pExpr; 411 }else{ 412 return pVector->x.pList->a[i].pExpr; 413 } 414 } 415 return pVector; 416 } 417 418 /* 419 ** Compute and return a new Expr object which when passed to 420 ** sqlite3ExprCode() will generate all necessary code to compute 421 ** the iField-th column of the vector expression pVector. 422 ** 423 ** It is ok for pVector to be a scalar (as long as iField==0). 424 ** In that case, this routine works like sqlite3ExprDup(). 425 ** 426 ** The caller owns the returned Expr object and is responsible for 427 ** ensuring that the returned value eventually gets freed. 428 ** 429 ** The caller retains ownership of pVector. If pVector is a TK_SELECT, 430 ** then the returned object will reference pVector and so pVector must remain 431 ** valid for the life of the returned object. If pVector is a TK_VECTOR 432 ** or a scalar expression, then it can be deleted as soon as this routine 433 ** returns. 434 ** 435 ** A trick to cause a TK_SELECT pVector to be deleted together with 436 ** the returned Expr object is to attach the pVector to the pRight field 437 ** of the returned TK_SELECT_COLUMN Expr object. 438 */ 439 Expr *sqlite3ExprForVectorField( 440 Parse *pParse, /* Parsing context */ 441 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */ 442 int iField /* Which column of the vector to return */ 443 ){ 444 Expr *pRet; 445 if( pVector->op==TK_SELECT ){ 446 assert( pVector->flags & EP_xIsSelect ); 447 /* The TK_SELECT_COLUMN Expr node: 448 ** 449 ** pLeft: pVector containing TK_SELECT. Not deleted. 450 ** pRight: not used. But recursively deleted. 451 ** iColumn: Index of a column in pVector 452 ** iTable: 0 or the number of columns on the LHS of an assignment 453 ** pLeft->iTable: First in an array of register holding result, or 0 454 ** if the result is not yet computed. 455 ** 456 ** sqlite3ExprDelete() specifically skips the recursive delete of 457 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector 458 ** can be attached to pRight to cause this node to take ownership of 459 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes 460 ** with the same pLeft pointer to the pVector, but only one of them 461 ** will own the pVector. 462 */ 463 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0); 464 if( pRet ){ 465 pRet->iColumn = iField; 466 pRet->pLeft = pVector; 467 } 468 assert( pRet==0 || pRet->iTable==0 ); 469 }else{ 470 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr; 471 pRet = sqlite3ExprDup(pParse->db, pVector, 0); 472 sqlite3RenameTokenRemap(pParse, pRet, pVector); 473 } 474 return pRet; 475 } 476 477 /* 478 ** If expression pExpr is of type TK_SELECT, generate code to evaluate 479 ** it. Return the register in which the result is stored (or, if the 480 ** sub-select returns more than one column, the first in an array 481 ** of registers in which the result is stored). 482 ** 483 ** If pExpr is not a TK_SELECT expression, return 0. 484 */ 485 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){ 486 int reg = 0; 487 #ifndef SQLITE_OMIT_SUBQUERY 488 if( pExpr->op==TK_SELECT ){ 489 reg = sqlite3CodeSubselect(pParse, pExpr); 490 } 491 #endif 492 return reg; 493 } 494 495 /* 496 ** Argument pVector points to a vector expression - either a TK_VECTOR 497 ** or TK_SELECT that returns more than one column. This function returns 498 ** the register number of a register that contains the value of 499 ** element iField of the vector. 500 ** 501 ** If pVector is a TK_SELECT expression, then code for it must have 502 ** already been generated using the exprCodeSubselect() routine. In this 503 ** case parameter regSelect should be the first in an array of registers 504 ** containing the results of the sub-select. 505 ** 506 ** If pVector is of type TK_VECTOR, then code for the requested field 507 ** is generated. In this case (*pRegFree) may be set to the number of 508 ** a temporary register to be freed by the caller before returning. 509 ** 510 ** Before returning, output parameter (*ppExpr) is set to point to the 511 ** Expr object corresponding to element iElem of the vector. 512 */ 513 static int exprVectorRegister( 514 Parse *pParse, /* Parse context */ 515 Expr *pVector, /* Vector to extract element from */ 516 int iField, /* Field to extract from pVector */ 517 int regSelect, /* First in array of registers */ 518 Expr **ppExpr, /* OUT: Expression element */ 519 int *pRegFree /* OUT: Temp register to free */ 520 ){ 521 u8 op = pVector->op; 522 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT ); 523 if( op==TK_REGISTER ){ 524 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField); 525 return pVector->iTable+iField; 526 } 527 if( op==TK_SELECT ){ 528 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr; 529 return regSelect+iField; 530 } 531 *ppExpr = pVector->x.pList->a[iField].pExpr; 532 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); 533 } 534 535 /* 536 ** Expression pExpr is a comparison between two vector values. Compute 537 ** the result of the comparison (1, 0, or NULL) and write that 538 ** result into register dest. 539 ** 540 ** The caller must satisfy the following preconditions: 541 ** 542 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ 543 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ 544 ** otherwise: op==pExpr->op and p5==0 545 */ 546 static void codeVectorCompare( 547 Parse *pParse, /* Code generator context */ 548 Expr *pExpr, /* The comparison operation */ 549 int dest, /* Write results into this register */ 550 u8 op, /* Comparison operator */ 551 u8 p5 /* SQLITE_NULLEQ or zero */ 552 ){ 553 Vdbe *v = pParse->pVdbe; 554 Expr *pLeft = pExpr->pLeft; 555 Expr *pRight = pExpr->pRight; 556 int nLeft = sqlite3ExprVectorSize(pLeft); 557 int i; 558 int regLeft = 0; 559 int regRight = 0; 560 u8 opx = op; 561 int addrDone = sqlite3VdbeMakeLabel(pParse); 562 563 if( nLeft!=sqlite3ExprVectorSize(pRight) ){ 564 sqlite3ErrorMsg(pParse, "row value misused"); 565 return; 566 } 567 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE 568 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT 569 || pExpr->op==TK_LT || pExpr->op==TK_GT 570 || pExpr->op==TK_LE || pExpr->op==TK_GE 571 ); 572 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ) 573 || (pExpr->op==TK_ISNOT && op==TK_NE) ); 574 assert( p5==0 || pExpr->op!=op ); 575 assert( p5==SQLITE_NULLEQ || pExpr->op==op ); 576 577 p5 |= SQLITE_STOREP2; 578 if( opx==TK_LE ) opx = TK_LT; 579 if( opx==TK_GE ) opx = TK_GT; 580 581 regLeft = exprCodeSubselect(pParse, pLeft); 582 regRight = exprCodeSubselect(pParse, pRight); 583 584 for(i=0; 1 /*Loop exits by "break"*/; i++){ 585 int regFree1 = 0, regFree2 = 0; 586 Expr *pL, *pR; 587 int r1, r2; 588 assert( i>=0 && i<nLeft ); 589 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1); 590 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2); 591 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5); 592 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 593 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 594 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 595 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 596 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); 597 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); 598 sqlite3ReleaseTempReg(pParse, regFree1); 599 sqlite3ReleaseTempReg(pParse, regFree2); 600 if( i==nLeft-1 ){ 601 break; 602 } 603 if( opx==TK_EQ ){ 604 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v); 605 p5 |= SQLITE_KEEPNULL; 606 }else if( opx==TK_NE ){ 607 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v); 608 p5 |= SQLITE_KEEPNULL; 609 }else{ 610 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE ); 611 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone); 612 VdbeCoverageIf(v, op==TK_LT); 613 VdbeCoverageIf(v, op==TK_GT); 614 VdbeCoverageIf(v, op==TK_LE); 615 VdbeCoverageIf(v, op==TK_GE); 616 if( i==nLeft-2 ) opx = op; 617 } 618 } 619 sqlite3VdbeResolveLabel(v, addrDone); 620 } 621 622 #if SQLITE_MAX_EXPR_DEPTH>0 623 /* 624 ** Check that argument nHeight is less than or equal to the maximum 625 ** expression depth allowed. If it is not, leave an error message in 626 ** pParse. 627 */ 628 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ 629 int rc = SQLITE_OK; 630 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; 631 if( nHeight>mxHeight ){ 632 sqlite3ErrorMsg(pParse, 633 "Expression tree is too large (maximum depth %d)", mxHeight 634 ); 635 rc = SQLITE_ERROR; 636 } 637 return rc; 638 } 639 640 /* The following three functions, heightOfExpr(), heightOfExprList() 641 ** and heightOfSelect(), are used to determine the maximum height 642 ** of any expression tree referenced by the structure passed as the 643 ** first argument. 644 ** 645 ** If this maximum height is greater than the current value pointed 646 ** to by pnHeight, the second parameter, then set *pnHeight to that 647 ** value. 648 */ 649 static void heightOfExpr(Expr *p, int *pnHeight){ 650 if( p ){ 651 if( p->nHeight>*pnHeight ){ 652 *pnHeight = p->nHeight; 653 } 654 } 655 } 656 static void heightOfExprList(ExprList *p, int *pnHeight){ 657 if( p ){ 658 int i; 659 for(i=0; i<p->nExpr; i++){ 660 heightOfExpr(p->a[i].pExpr, pnHeight); 661 } 662 } 663 } 664 static void heightOfSelect(Select *pSelect, int *pnHeight){ 665 Select *p; 666 for(p=pSelect; p; p=p->pPrior){ 667 heightOfExpr(p->pWhere, pnHeight); 668 heightOfExpr(p->pHaving, pnHeight); 669 heightOfExpr(p->pLimit, pnHeight); 670 heightOfExprList(p->pEList, pnHeight); 671 heightOfExprList(p->pGroupBy, pnHeight); 672 heightOfExprList(p->pOrderBy, pnHeight); 673 } 674 } 675 676 /* 677 ** Set the Expr.nHeight variable in the structure passed as an 678 ** argument. An expression with no children, Expr.pList or 679 ** Expr.pSelect member has a height of 1. Any other expression 680 ** has a height equal to the maximum height of any other 681 ** referenced Expr plus one. 682 ** 683 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags, 684 ** if appropriate. 685 */ 686 static void exprSetHeight(Expr *p){ 687 int nHeight = 0; 688 heightOfExpr(p->pLeft, &nHeight); 689 heightOfExpr(p->pRight, &nHeight); 690 if( ExprHasProperty(p, EP_xIsSelect) ){ 691 heightOfSelect(p->x.pSelect, &nHeight); 692 }else if( p->x.pList ){ 693 heightOfExprList(p->x.pList, &nHeight); 694 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); 695 } 696 p->nHeight = nHeight + 1; 697 } 698 699 /* 700 ** Set the Expr.nHeight variable using the exprSetHeight() function. If 701 ** the height is greater than the maximum allowed expression depth, 702 ** leave an error in pParse. 703 ** 704 ** Also propagate all EP_Propagate flags from the Expr.x.pList into 705 ** Expr.flags. 706 */ 707 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ 708 if( pParse->nErr ) return; 709 exprSetHeight(p); 710 sqlite3ExprCheckHeight(pParse, p->nHeight); 711 } 712 713 /* 714 ** Return the maximum height of any expression tree referenced 715 ** by the select statement passed as an argument. 716 */ 717 int sqlite3SelectExprHeight(Select *p){ 718 int nHeight = 0; 719 heightOfSelect(p, &nHeight); 720 return nHeight; 721 } 722 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */ 723 /* 724 ** Propagate all EP_Propagate flags from the Expr.x.pList into 725 ** Expr.flags. 726 */ 727 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ 728 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){ 729 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); 730 } 731 } 732 #define exprSetHeight(y) 733 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */ 734 735 /* 736 ** This routine is the core allocator for Expr nodes. 737 ** 738 ** Construct a new expression node and return a pointer to it. Memory 739 ** for this node and for the pToken argument is a single allocation 740 ** obtained from sqlite3DbMalloc(). The calling function 741 ** is responsible for making sure the node eventually gets freed. 742 ** 743 ** If dequote is true, then the token (if it exists) is dequoted. 744 ** If dequote is false, no dequoting is performed. The deQuote 745 ** parameter is ignored if pToken is NULL or if the token does not 746 ** appear to be quoted. If the quotes were of the form "..." (double-quotes) 747 ** then the EP_DblQuoted flag is set on the expression node. 748 ** 749 ** Special case: If op==TK_INTEGER and pToken points to a string that 750 ** can be translated into a 32-bit integer, then the token is not 751 ** stored in u.zToken. Instead, the integer values is written 752 ** into u.iValue and the EP_IntValue flag is set. No extra storage 753 ** is allocated to hold the integer text and the dequote flag is ignored. 754 */ 755 Expr *sqlite3ExprAlloc( 756 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */ 757 int op, /* Expression opcode */ 758 const Token *pToken, /* Token argument. Might be NULL */ 759 int dequote /* True to dequote */ 760 ){ 761 Expr *pNew; 762 int nExtra = 0; 763 int iValue = 0; 764 765 assert( db!=0 ); 766 if( pToken ){ 767 if( op!=TK_INTEGER || pToken->z==0 768 || sqlite3GetInt32(pToken->z, &iValue)==0 ){ 769 nExtra = pToken->n+1; 770 assert( iValue>=0 ); 771 } 772 } 773 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); 774 if( pNew ){ 775 memset(pNew, 0, sizeof(Expr)); 776 pNew->op = (u8)op; 777 pNew->iAgg = -1; 778 if( pToken ){ 779 if( nExtra==0 ){ 780 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse); 781 pNew->u.iValue = iValue; 782 }else{ 783 pNew->u.zToken = (char*)&pNew[1]; 784 assert( pToken->z!=0 || pToken->n==0 ); 785 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); 786 pNew->u.zToken[pToken->n] = 0; 787 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ 788 sqlite3DequoteExpr(pNew); 789 } 790 } 791 } 792 #if SQLITE_MAX_EXPR_DEPTH>0 793 pNew->nHeight = 1; 794 #endif 795 } 796 return pNew; 797 } 798 799 /* 800 ** Allocate a new expression node from a zero-terminated token that has 801 ** already been dequoted. 802 */ 803 Expr *sqlite3Expr( 804 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ 805 int op, /* Expression opcode */ 806 const char *zToken /* Token argument. Might be NULL */ 807 ){ 808 Token x; 809 x.z = zToken; 810 x.n = sqlite3Strlen30(zToken); 811 return sqlite3ExprAlloc(db, op, &x, 0); 812 } 813 814 /* 815 ** Attach subtrees pLeft and pRight to the Expr node pRoot. 816 ** 817 ** If pRoot==NULL that means that a memory allocation error has occurred. 818 ** In that case, delete the subtrees pLeft and pRight. 819 */ 820 void sqlite3ExprAttachSubtrees( 821 sqlite3 *db, 822 Expr *pRoot, 823 Expr *pLeft, 824 Expr *pRight 825 ){ 826 if( pRoot==0 ){ 827 assert( db->mallocFailed ); 828 sqlite3ExprDelete(db, pLeft); 829 sqlite3ExprDelete(db, pRight); 830 }else{ 831 if( pRight ){ 832 pRoot->pRight = pRight; 833 pRoot->flags |= EP_Propagate & pRight->flags; 834 } 835 if( pLeft ){ 836 pRoot->pLeft = pLeft; 837 pRoot->flags |= EP_Propagate & pLeft->flags; 838 } 839 exprSetHeight(pRoot); 840 } 841 } 842 843 /* 844 ** Allocate an Expr node which joins as many as two subtrees. 845 ** 846 ** One or both of the subtrees can be NULL. Return a pointer to the new 847 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, 848 ** free the subtrees and return NULL. 849 */ 850 Expr *sqlite3PExpr( 851 Parse *pParse, /* Parsing context */ 852 int op, /* Expression opcode */ 853 Expr *pLeft, /* Left operand */ 854 Expr *pRight /* Right operand */ 855 ){ 856 Expr *p; 857 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)); 858 if( p ){ 859 memset(p, 0, sizeof(Expr)); 860 p->op = op & 0xff; 861 p->iAgg = -1; 862 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); 863 sqlite3ExprCheckHeight(pParse, p->nHeight); 864 }else{ 865 sqlite3ExprDelete(pParse->db, pLeft); 866 sqlite3ExprDelete(pParse->db, pRight); 867 } 868 return p; 869 } 870 871 /* 872 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due 873 ** do a memory allocation failure) then delete the pSelect object. 874 */ 875 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ 876 if( pExpr ){ 877 pExpr->x.pSelect = pSelect; 878 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery); 879 sqlite3ExprSetHeightAndFlags(pParse, pExpr); 880 }else{ 881 assert( pParse->db->mallocFailed ); 882 sqlite3SelectDelete(pParse->db, pSelect); 883 } 884 } 885 886 887 /* 888 ** Join two expressions using an AND operator. If either expression is 889 ** NULL, then just return the other expression. 890 ** 891 ** If one side or the other of the AND is known to be false, then instead 892 ** of returning an AND expression, just return a constant expression with 893 ** a value of false. 894 */ 895 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){ 896 sqlite3 *db = pParse->db; 897 if( pLeft==0 ){ 898 return pRight; 899 }else if( pRight==0 ){ 900 return pLeft; 901 }else if( ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight) ){ 902 sqlite3ExprUnmapAndDelete(pParse, pLeft); 903 sqlite3ExprUnmapAndDelete(pParse, pRight); 904 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0); 905 }else{ 906 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight); 907 } 908 } 909 910 /* 911 ** Construct a new expression node for a function with multiple 912 ** arguments. 913 */ 914 Expr *sqlite3ExprFunction( 915 Parse *pParse, /* Parsing context */ 916 ExprList *pList, /* Argument list */ 917 Token *pToken, /* Name of the function */ 918 int eDistinct /* SF_Distinct or SF_ALL or 0 */ 919 ){ 920 Expr *pNew; 921 sqlite3 *db = pParse->db; 922 assert( pToken ); 923 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); 924 if( pNew==0 ){ 925 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ 926 return 0; 927 } 928 if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){ 929 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken); 930 } 931 pNew->x.pList = pList; 932 ExprSetProperty(pNew, EP_HasFunc); 933 assert( !ExprHasProperty(pNew, EP_xIsSelect) ); 934 sqlite3ExprSetHeightAndFlags(pParse, pNew); 935 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct); 936 return pNew; 937 } 938 939 /* 940 ** Assign a variable number to an expression that encodes a wildcard 941 ** in the original SQL statement. 942 ** 943 ** Wildcards consisting of a single "?" are assigned the next sequential 944 ** variable number. 945 ** 946 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make 947 ** sure "nnn" is not too big to avoid a denial of service attack when 948 ** the SQL statement comes from an external source. 949 ** 950 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number 951 ** as the previous instance of the same wildcard. Or if this is the first 952 ** instance of the wildcard, the next sequential variable number is 953 ** assigned. 954 */ 955 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ 956 sqlite3 *db = pParse->db; 957 const char *z; 958 ynVar x; 959 960 if( pExpr==0 ) return; 961 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); 962 z = pExpr->u.zToken; 963 assert( z!=0 ); 964 assert( z[0]!=0 ); 965 assert( n==(u32)sqlite3Strlen30(z) ); 966 if( z[1]==0 ){ 967 /* Wildcard of the form "?". Assign the next variable number */ 968 assert( z[0]=='?' ); 969 x = (ynVar)(++pParse->nVar); 970 }else{ 971 int doAdd = 0; 972 if( z[0]=='?' ){ 973 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and 974 ** use it as the variable number */ 975 i64 i; 976 int bOk; 977 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/ 978 i = z[1]-'0'; /* The common case of ?N for a single digit N */ 979 bOk = 1; 980 }else{ 981 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); 982 } 983 testcase( i==0 ); 984 testcase( i==1 ); 985 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); 986 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); 987 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 988 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", 989 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); 990 return; 991 } 992 x = (ynVar)i; 993 if( x>pParse->nVar ){ 994 pParse->nVar = (int)x; 995 doAdd = 1; 996 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){ 997 doAdd = 1; 998 } 999 }else{ 1000 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable 1001 ** number as the prior appearance of the same name, or if the name 1002 ** has never appeared before, reuse the same variable number 1003 */ 1004 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n); 1005 if( x==0 ){ 1006 x = (ynVar)(++pParse->nVar); 1007 doAdd = 1; 1008 } 1009 } 1010 if( doAdd ){ 1011 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x); 1012 } 1013 } 1014 pExpr->iColumn = x; 1015 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 1016 sqlite3ErrorMsg(pParse, "too many SQL variables"); 1017 } 1018 } 1019 1020 /* 1021 ** Recursively delete an expression tree. 1022 */ 1023 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ 1024 assert( p!=0 ); 1025 /* Sanity check: Assert that the IntValue is non-negative if it exists */ 1026 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 ); 1027 1028 assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed ); 1029 assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced) 1030 || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) ); 1031 #ifdef SQLITE_DEBUG 1032 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){ 1033 assert( p->pLeft==0 ); 1034 assert( p->pRight==0 ); 1035 assert( p->x.pSelect==0 ); 1036 } 1037 #endif 1038 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){ 1039 /* The Expr.x union is never used at the same time as Expr.pRight */ 1040 assert( p->x.pList==0 || p->pRight==0 ); 1041 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft); 1042 if( p->pRight ){ 1043 assert( !ExprHasProperty(p, EP_WinFunc) ); 1044 sqlite3ExprDeleteNN(db, p->pRight); 1045 }else if( ExprHasProperty(p, EP_xIsSelect) ){ 1046 assert( !ExprHasProperty(p, EP_WinFunc) ); 1047 sqlite3SelectDelete(db, p->x.pSelect); 1048 }else{ 1049 sqlite3ExprListDelete(db, p->x.pList); 1050 #ifndef SQLITE_OMIT_WINDOWFUNC 1051 if( ExprHasProperty(p, EP_WinFunc) ){ 1052 sqlite3WindowDelete(db, p->y.pWin); 1053 } 1054 #endif 1055 } 1056 } 1057 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken); 1058 if( !ExprHasProperty(p, EP_Static) ){ 1059 sqlite3DbFreeNN(db, p); 1060 } 1061 } 1062 void sqlite3ExprDelete(sqlite3 *db, Expr *p){ 1063 if( p ) sqlite3ExprDeleteNN(db, p); 1064 } 1065 1066 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the 1067 ** expression. 1068 */ 1069 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){ 1070 if( p ){ 1071 if( IN_RENAME_OBJECT ){ 1072 sqlite3RenameExprUnmap(pParse, p); 1073 } 1074 sqlite3ExprDeleteNN(pParse->db, p); 1075 } 1076 } 1077 1078 /* 1079 ** Return the number of bytes allocated for the expression structure 1080 ** passed as the first argument. This is always one of EXPR_FULLSIZE, 1081 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. 1082 */ 1083 static int exprStructSize(Expr *p){ 1084 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; 1085 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; 1086 return EXPR_FULLSIZE; 1087 } 1088 1089 /* 1090 ** The dupedExpr*Size() routines each return the number of bytes required 1091 ** to store a copy of an expression or expression tree. They differ in 1092 ** how much of the tree is measured. 1093 ** 1094 ** dupedExprStructSize() Size of only the Expr structure 1095 ** dupedExprNodeSize() Size of Expr + space for token 1096 ** dupedExprSize() Expr + token + subtree components 1097 ** 1098 *************************************************************************** 1099 ** 1100 ** The dupedExprStructSize() function returns two values OR-ed together: 1101 ** (1) the space required for a copy of the Expr structure only and 1102 ** (2) the EP_xxx flags that indicate what the structure size should be. 1103 ** The return values is always one of: 1104 ** 1105 ** EXPR_FULLSIZE 1106 ** EXPR_REDUCEDSIZE | EP_Reduced 1107 ** EXPR_TOKENONLYSIZE | EP_TokenOnly 1108 ** 1109 ** The size of the structure can be found by masking the return value 1110 ** of this routine with 0xfff. The flags can be found by masking the 1111 ** return value with EP_Reduced|EP_TokenOnly. 1112 ** 1113 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size 1114 ** (unreduced) Expr objects as they or originally constructed by the parser. 1115 ** During expression analysis, extra information is computed and moved into 1116 ** later parts of the Expr object and that extra information might get chopped 1117 ** off if the expression is reduced. Note also that it does not work to 1118 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal 1119 ** to reduce a pristine expression tree from the parser. The implementation 1120 ** of dupedExprStructSize() contain multiple assert() statements that attempt 1121 ** to enforce this constraint. 1122 */ 1123 static int dupedExprStructSize(Expr *p, int flags){ 1124 int nSize; 1125 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ 1126 assert( EXPR_FULLSIZE<=0xfff ); 1127 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); 1128 if( 0==flags || p->op==TK_SELECT_COLUMN 1129 #ifndef SQLITE_OMIT_WINDOWFUNC 1130 || ExprHasProperty(p, EP_WinFunc) 1131 #endif 1132 ){ 1133 nSize = EXPR_FULLSIZE; 1134 }else{ 1135 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 1136 assert( !ExprHasProperty(p, EP_FromJoin) ); 1137 assert( !ExprHasProperty(p, EP_MemToken) ); 1138 assert( !ExprHasProperty(p, EP_NoReduce) ); 1139 if( p->pLeft || p->x.pList ){ 1140 nSize = EXPR_REDUCEDSIZE | EP_Reduced; 1141 }else{ 1142 assert( p->pRight==0 ); 1143 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; 1144 } 1145 } 1146 return nSize; 1147 } 1148 1149 /* 1150 ** This function returns the space in bytes required to store the copy 1151 ** of the Expr structure and a copy of the Expr.u.zToken string (if that 1152 ** string is defined.) 1153 */ 1154 static int dupedExprNodeSize(Expr *p, int flags){ 1155 int nByte = dupedExprStructSize(p, flags) & 0xfff; 1156 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 1157 nByte += sqlite3Strlen30NN(p->u.zToken)+1; 1158 } 1159 return ROUND8(nByte); 1160 } 1161 1162 /* 1163 ** Return the number of bytes required to create a duplicate of the 1164 ** expression passed as the first argument. The second argument is a 1165 ** mask containing EXPRDUP_XXX flags. 1166 ** 1167 ** The value returned includes space to create a copy of the Expr struct 1168 ** itself and the buffer referred to by Expr.u.zToken, if any. 1169 ** 1170 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 1171 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 1172 ** and Expr.pRight variables (but not for any structures pointed to or 1173 ** descended from the Expr.x.pList or Expr.x.pSelect variables). 1174 */ 1175 static int dupedExprSize(Expr *p, int flags){ 1176 int nByte = 0; 1177 if( p ){ 1178 nByte = dupedExprNodeSize(p, flags); 1179 if( flags&EXPRDUP_REDUCE ){ 1180 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags); 1181 } 1182 } 1183 return nByte; 1184 } 1185 1186 /* 1187 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 1188 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 1189 ** to store the copy of expression p, the copies of p->u.zToken 1190 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions, 1191 ** if any. Before returning, *pzBuffer is set to the first byte past the 1192 ** portion of the buffer copied into by this function. 1193 */ 1194 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ 1195 Expr *pNew; /* Value to return */ 1196 u8 *zAlloc; /* Memory space from which to build Expr object */ 1197 u32 staticFlag; /* EP_Static if space not obtained from malloc */ 1198 1199 assert( db!=0 ); 1200 assert( p ); 1201 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE ); 1202 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE ); 1203 1204 /* Figure out where to write the new Expr structure. */ 1205 if( pzBuffer ){ 1206 zAlloc = *pzBuffer; 1207 staticFlag = EP_Static; 1208 }else{ 1209 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags)); 1210 staticFlag = 0; 1211 } 1212 pNew = (Expr *)zAlloc; 1213 1214 if( pNew ){ 1215 /* Set nNewSize to the size allocated for the structure pointed to 1216 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or 1217 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed 1218 ** by the copy of the p->u.zToken string (if any). 1219 */ 1220 const unsigned nStructSize = dupedExprStructSize(p, dupFlags); 1221 const int nNewSize = nStructSize & 0xfff; 1222 int nToken; 1223 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 1224 nToken = sqlite3Strlen30(p->u.zToken) + 1; 1225 }else{ 1226 nToken = 0; 1227 } 1228 if( dupFlags ){ 1229 assert( ExprHasProperty(p, EP_Reduced)==0 ); 1230 memcpy(zAlloc, p, nNewSize); 1231 }else{ 1232 u32 nSize = (u32)exprStructSize(p); 1233 memcpy(zAlloc, p, nSize); 1234 if( nSize<EXPR_FULLSIZE ){ 1235 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize); 1236 } 1237 } 1238 1239 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ 1240 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken); 1241 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); 1242 pNew->flags |= staticFlag; 1243 1244 /* Copy the p->u.zToken string, if any. */ 1245 if( nToken ){ 1246 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; 1247 memcpy(zToken, p->u.zToken, nToken); 1248 } 1249 1250 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){ 1251 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ 1252 if( ExprHasProperty(p, EP_xIsSelect) ){ 1253 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags); 1254 }else{ 1255 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags); 1256 } 1257 } 1258 1259 /* Fill in pNew->pLeft and pNew->pRight. */ 1260 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){ 1261 zAlloc += dupedExprNodeSize(p, dupFlags); 1262 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){ 1263 pNew->pLeft = p->pLeft ? 1264 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0; 1265 pNew->pRight = p->pRight ? 1266 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0; 1267 } 1268 #ifndef SQLITE_OMIT_WINDOWFUNC 1269 if( ExprHasProperty(p, EP_WinFunc) ){ 1270 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin); 1271 assert( ExprHasProperty(pNew, EP_WinFunc) ); 1272 } 1273 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1274 if( pzBuffer ){ 1275 *pzBuffer = zAlloc; 1276 } 1277 }else{ 1278 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ 1279 if( pNew->op==TK_SELECT_COLUMN ){ 1280 pNew->pLeft = p->pLeft; 1281 assert( p->iColumn==0 || p->pRight==0 ); 1282 assert( p->pRight==0 || p->pRight==p->pLeft ); 1283 }else{ 1284 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); 1285 } 1286 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); 1287 } 1288 } 1289 } 1290 return pNew; 1291 } 1292 1293 /* 1294 ** Create and return a deep copy of the object passed as the second 1295 ** argument. If an OOM condition is encountered, NULL is returned 1296 ** and the db->mallocFailed flag set. 1297 */ 1298 #ifndef SQLITE_OMIT_CTE 1299 static With *withDup(sqlite3 *db, With *p){ 1300 With *pRet = 0; 1301 if( p ){ 1302 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); 1303 pRet = sqlite3DbMallocZero(db, nByte); 1304 if( pRet ){ 1305 int i; 1306 pRet->nCte = p->nCte; 1307 for(i=0; i<p->nCte; i++){ 1308 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0); 1309 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0); 1310 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName); 1311 } 1312 } 1313 } 1314 return pRet; 1315 } 1316 #else 1317 # define withDup(x,y) 0 1318 #endif 1319 1320 #ifndef SQLITE_OMIT_WINDOWFUNC 1321 /* 1322 ** The gatherSelectWindows() procedure and its helper routine 1323 ** gatherSelectWindowsCallback() are used to scan all the expressions 1324 ** an a newly duplicated SELECT statement and gather all of the Window 1325 ** objects found there, assembling them onto the linked list at Select->pWin. 1326 */ 1327 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){ 1328 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){ 1329 Select *pSelect = pWalker->u.pSelect; 1330 Window *pWin = pExpr->y.pWin; 1331 assert( pWin ); 1332 assert( IsWindowFunc(pExpr) ); 1333 assert( pWin->ppThis==0 ); 1334 if( pSelect->pWin ){ 1335 pSelect->pWin->ppThis = &pWin->pNextWin; 1336 } 1337 pWin->pNextWin = pSelect->pWin; 1338 pWin->ppThis = &pSelect->pWin; 1339 pSelect->pWin = pWin; 1340 } 1341 return WRC_Continue; 1342 } 1343 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){ 1344 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune; 1345 } 1346 static void gatherSelectWindows(Select *p){ 1347 Walker w; 1348 w.xExprCallback = gatherSelectWindowsCallback; 1349 w.xSelectCallback = gatherSelectWindowsSelectCallback; 1350 w.xSelectCallback2 = 0; 1351 w.pParse = 0; 1352 w.u.pSelect = p; 1353 sqlite3WalkSelect(&w, p); 1354 } 1355 #endif 1356 1357 1358 /* 1359 ** The following group of routines make deep copies of expressions, 1360 ** expression lists, ID lists, and select statements. The copies can 1361 ** be deleted (by being passed to their respective ...Delete() routines) 1362 ** without effecting the originals. 1363 ** 1364 ** The expression list, ID, and source lists return by sqlite3ExprListDup(), 1365 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 1366 ** by subsequent calls to sqlite*ListAppend() routines. 1367 ** 1368 ** Any tables that the SrcList might point to are not duplicated. 1369 ** 1370 ** The flags parameter contains a combination of the EXPRDUP_XXX flags. 1371 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a 1372 ** truncated version of the usual Expr structure that will be stored as 1373 ** part of the in-memory representation of the database schema. 1374 */ 1375 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ 1376 assert( flags==0 || flags==EXPRDUP_REDUCE ); 1377 return p ? exprDup(db, p, flags, 0) : 0; 1378 } 1379 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ 1380 ExprList *pNew; 1381 struct ExprList_item *pItem, *pOldItem; 1382 int i; 1383 Expr *pPriorSelectCol = 0; 1384 assert( db!=0 ); 1385 if( p==0 ) return 0; 1386 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p)); 1387 if( pNew==0 ) return 0; 1388 pNew->nExpr = p->nExpr; 1389 pItem = pNew->a; 1390 pOldItem = p->a; 1391 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){ 1392 Expr *pOldExpr = pOldItem->pExpr; 1393 Expr *pNewExpr; 1394 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); 1395 if( pOldExpr 1396 && pOldExpr->op==TK_SELECT_COLUMN 1397 && (pNewExpr = pItem->pExpr)!=0 1398 ){ 1399 assert( pNewExpr->iColumn==0 || i>0 ); 1400 if( pNewExpr->iColumn==0 ){ 1401 assert( pOldExpr->pLeft==pOldExpr->pRight ); 1402 pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight; 1403 }else{ 1404 assert( i>0 ); 1405 assert( pItem[-1].pExpr!=0 ); 1406 assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 ); 1407 assert( pPriorSelectCol==pItem[-1].pExpr->pLeft ); 1408 pNewExpr->pLeft = pPriorSelectCol; 1409 } 1410 } 1411 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 1412 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan); 1413 pItem->sortOrder = pOldItem->sortOrder; 1414 pItem->done = 0; 1415 pItem->bSpanIsTab = pOldItem->bSpanIsTab; 1416 pItem->bSorterRef = pOldItem->bSorterRef; 1417 pItem->u = pOldItem->u; 1418 } 1419 return pNew; 1420 } 1421 1422 /* 1423 ** If cursors, triggers, views and subqueries are all omitted from 1424 ** the build, then none of the following routines, except for 1425 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes 1426 ** called with a NULL argument. 1427 */ 1428 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ 1429 || !defined(SQLITE_OMIT_SUBQUERY) 1430 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ 1431 SrcList *pNew; 1432 int i; 1433 int nByte; 1434 assert( db!=0 ); 1435 if( p==0 ) return 0; 1436 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); 1437 pNew = sqlite3DbMallocRawNN(db, nByte ); 1438 if( pNew==0 ) return 0; 1439 pNew->nSrc = pNew->nAlloc = p->nSrc; 1440 for(i=0; i<p->nSrc; i++){ 1441 struct SrcList_item *pNewItem = &pNew->a[i]; 1442 struct SrcList_item *pOldItem = &p->a[i]; 1443 Table *pTab; 1444 pNewItem->pSchema = pOldItem->pSchema; 1445 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); 1446 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 1447 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); 1448 pNewItem->fg = pOldItem->fg; 1449 pNewItem->iCursor = pOldItem->iCursor; 1450 pNewItem->addrFillSub = pOldItem->addrFillSub; 1451 pNewItem->regReturn = pOldItem->regReturn; 1452 if( pNewItem->fg.isIndexedBy ){ 1453 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); 1454 } 1455 pNewItem->pIBIndex = pOldItem->pIBIndex; 1456 if( pNewItem->fg.isTabFunc ){ 1457 pNewItem->u1.pFuncArg = 1458 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); 1459 } 1460 pTab = pNewItem->pTab = pOldItem->pTab; 1461 if( pTab ){ 1462 pTab->nTabRef++; 1463 } 1464 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); 1465 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); 1466 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); 1467 pNewItem->colUsed = pOldItem->colUsed; 1468 } 1469 return pNew; 1470 } 1471 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ 1472 IdList *pNew; 1473 int i; 1474 assert( db!=0 ); 1475 if( p==0 ) return 0; 1476 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); 1477 if( pNew==0 ) return 0; 1478 pNew->nId = p->nId; 1479 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) ); 1480 if( pNew->a==0 ){ 1481 sqlite3DbFreeNN(db, pNew); 1482 return 0; 1483 } 1484 /* Note that because the size of the allocation for p->a[] is not 1485 ** necessarily a power of two, sqlite3IdListAppend() may not be called 1486 ** on the duplicate created by this function. */ 1487 for(i=0; i<p->nId; i++){ 1488 struct IdList_item *pNewItem = &pNew->a[i]; 1489 struct IdList_item *pOldItem = &p->a[i]; 1490 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 1491 pNewItem->idx = pOldItem->idx; 1492 } 1493 return pNew; 1494 } 1495 Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){ 1496 Select *pRet = 0; 1497 Select *pNext = 0; 1498 Select **pp = &pRet; 1499 Select *p; 1500 1501 assert( db!=0 ); 1502 for(p=pDup; p; p=p->pPrior){ 1503 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) ); 1504 if( pNew==0 ) break; 1505 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); 1506 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); 1507 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); 1508 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); 1509 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); 1510 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); 1511 pNew->op = p->op; 1512 pNew->pNext = pNext; 1513 pNew->pPrior = 0; 1514 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); 1515 pNew->iLimit = 0; 1516 pNew->iOffset = 0; 1517 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; 1518 pNew->addrOpenEphm[0] = -1; 1519 pNew->addrOpenEphm[1] = -1; 1520 pNew->nSelectRow = p->nSelectRow; 1521 pNew->pWith = withDup(db, p->pWith); 1522 #ifndef SQLITE_OMIT_WINDOWFUNC 1523 pNew->pWin = 0; 1524 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn); 1525 if( p->pWin ) gatherSelectWindows(pNew); 1526 #endif 1527 pNew->selId = p->selId; 1528 *pp = pNew; 1529 pp = &pNew->pPrior; 1530 pNext = pNew; 1531 } 1532 1533 return pRet; 1534 } 1535 #else 1536 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ 1537 assert( p==0 ); 1538 return 0; 1539 } 1540 #endif 1541 1542 1543 /* 1544 ** Add a new element to the end of an expression list. If pList is 1545 ** initially NULL, then create a new expression list. 1546 ** 1547 ** The pList argument must be either NULL or a pointer to an ExprList 1548 ** obtained from a prior call to sqlite3ExprListAppend(). This routine 1549 ** may not be used with an ExprList obtained from sqlite3ExprListDup(). 1550 ** Reason: This routine assumes that the number of slots in pList->a[] 1551 ** is a power of two. That is true for sqlite3ExprListAppend() returns 1552 ** but is not necessarily true from the return value of sqlite3ExprListDup(). 1553 ** 1554 ** If a memory allocation error occurs, the entire list is freed and 1555 ** NULL is returned. If non-NULL is returned, then it is guaranteed 1556 ** that the new entry was successfully appended. 1557 */ 1558 ExprList *sqlite3ExprListAppend( 1559 Parse *pParse, /* Parsing context */ 1560 ExprList *pList, /* List to which to append. Might be NULL */ 1561 Expr *pExpr /* Expression to be appended. Might be NULL */ 1562 ){ 1563 struct ExprList_item *pItem; 1564 sqlite3 *db = pParse->db; 1565 assert( db!=0 ); 1566 if( pList==0 ){ 1567 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) ); 1568 if( pList==0 ){ 1569 goto no_mem; 1570 } 1571 pList->nExpr = 0; 1572 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){ 1573 ExprList *pNew; 1574 pNew = sqlite3DbRealloc(db, pList, 1575 sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0])); 1576 if( pNew==0 ){ 1577 goto no_mem; 1578 } 1579 pList = pNew; 1580 } 1581 pItem = &pList->a[pList->nExpr++]; 1582 assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) ); 1583 assert( offsetof(struct ExprList_item,pExpr)==0 ); 1584 memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName)); 1585 pItem->pExpr = pExpr; 1586 return pList; 1587 1588 no_mem: 1589 /* Avoid leaking memory if malloc has failed. */ 1590 sqlite3ExprDelete(db, pExpr); 1591 sqlite3ExprListDelete(db, pList); 1592 return 0; 1593 } 1594 1595 /* 1596 ** pColumns and pExpr form a vector assignment which is part of the SET 1597 ** clause of an UPDATE statement. Like this: 1598 ** 1599 ** (a,b,c) = (expr1,expr2,expr3) 1600 ** Or: (a,b,c) = (SELECT x,y,z FROM ....) 1601 ** 1602 ** For each term of the vector assignment, append new entries to the 1603 ** expression list pList. In the case of a subquery on the RHS, append 1604 ** TK_SELECT_COLUMN expressions. 1605 */ 1606 ExprList *sqlite3ExprListAppendVector( 1607 Parse *pParse, /* Parsing context */ 1608 ExprList *pList, /* List to which to append. Might be NULL */ 1609 IdList *pColumns, /* List of names of LHS of the assignment */ 1610 Expr *pExpr /* Vector expression to be appended. Might be NULL */ 1611 ){ 1612 sqlite3 *db = pParse->db; 1613 int n; 1614 int i; 1615 int iFirst = pList ? pList->nExpr : 0; 1616 /* pColumns can only be NULL due to an OOM but an OOM will cause an 1617 ** exit prior to this routine being invoked */ 1618 if( NEVER(pColumns==0) ) goto vector_append_error; 1619 if( pExpr==0 ) goto vector_append_error; 1620 1621 /* If the RHS is a vector, then we can immediately check to see that 1622 ** the size of the RHS and LHS match. But if the RHS is a SELECT, 1623 ** wildcards ("*") in the result set of the SELECT must be expanded before 1624 ** we can do the size check, so defer the size check until code generation. 1625 */ 1626 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){ 1627 sqlite3ErrorMsg(pParse, "%d columns assigned %d values", 1628 pColumns->nId, n); 1629 goto vector_append_error; 1630 } 1631 1632 for(i=0; i<pColumns->nId; i++){ 1633 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i); 1634 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr); 1635 if( pList ){ 1636 assert( pList->nExpr==iFirst+i+1 ); 1637 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName; 1638 pColumns->a[i].zName = 0; 1639 } 1640 } 1641 1642 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){ 1643 Expr *pFirst = pList->a[iFirst].pExpr; 1644 assert( pFirst!=0 ); 1645 assert( pFirst->op==TK_SELECT_COLUMN ); 1646 1647 /* Store the SELECT statement in pRight so it will be deleted when 1648 ** sqlite3ExprListDelete() is called */ 1649 pFirst->pRight = pExpr; 1650 pExpr = 0; 1651 1652 /* Remember the size of the LHS in iTable so that we can check that 1653 ** the RHS and LHS sizes match during code generation. */ 1654 pFirst->iTable = pColumns->nId; 1655 } 1656 1657 vector_append_error: 1658 sqlite3ExprUnmapAndDelete(pParse, pExpr); 1659 sqlite3IdListDelete(db, pColumns); 1660 return pList; 1661 } 1662 1663 /* 1664 ** Set the sort order for the last element on the given ExprList. 1665 */ 1666 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){ 1667 if( p==0 ) return; 1668 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 ); 1669 assert( p->nExpr>0 ); 1670 if( iSortOrder<0 ){ 1671 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC ); 1672 return; 1673 } 1674 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder; 1675 } 1676 1677 /* 1678 ** Set the ExprList.a[].zName element of the most recently added item 1679 ** on the expression list. 1680 ** 1681 ** pList might be NULL following an OOM error. But pName should never be 1682 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 1683 ** is set. 1684 */ 1685 void sqlite3ExprListSetName( 1686 Parse *pParse, /* Parsing context */ 1687 ExprList *pList, /* List to which to add the span. */ 1688 Token *pName, /* Name to be added */ 1689 int dequote /* True to cause the name to be dequoted */ 1690 ){ 1691 assert( pList!=0 || pParse->db->mallocFailed!=0 ); 1692 if( pList ){ 1693 struct ExprList_item *pItem; 1694 assert( pList->nExpr>0 ); 1695 pItem = &pList->a[pList->nExpr-1]; 1696 assert( pItem->zName==0 ); 1697 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); 1698 if( dequote ) sqlite3Dequote(pItem->zName); 1699 if( IN_RENAME_OBJECT ){ 1700 sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName); 1701 } 1702 } 1703 } 1704 1705 /* 1706 ** Set the ExprList.a[].zSpan element of the most recently added item 1707 ** on the expression list. 1708 ** 1709 ** pList might be NULL following an OOM error. But pSpan should never be 1710 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 1711 ** is set. 1712 */ 1713 void sqlite3ExprListSetSpan( 1714 Parse *pParse, /* Parsing context */ 1715 ExprList *pList, /* List to which to add the span. */ 1716 const char *zStart, /* Start of the span */ 1717 const char *zEnd /* End of the span */ 1718 ){ 1719 sqlite3 *db = pParse->db; 1720 assert( pList!=0 || db->mallocFailed!=0 ); 1721 if( pList ){ 1722 struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; 1723 assert( pList->nExpr>0 ); 1724 sqlite3DbFree(db, pItem->zSpan); 1725 pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd); 1726 } 1727 } 1728 1729 /* 1730 ** If the expression list pEList contains more than iLimit elements, 1731 ** leave an error message in pParse. 1732 */ 1733 void sqlite3ExprListCheckLength( 1734 Parse *pParse, 1735 ExprList *pEList, 1736 const char *zObject 1737 ){ 1738 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; 1739 testcase( pEList && pEList->nExpr==mx ); 1740 testcase( pEList && pEList->nExpr==mx+1 ); 1741 if( pEList && pEList->nExpr>mx ){ 1742 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); 1743 } 1744 } 1745 1746 /* 1747 ** Delete an entire expression list. 1748 */ 1749 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){ 1750 int i = pList->nExpr; 1751 struct ExprList_item *pItem = pList->a; 1752 assert( pList->nExpr>0 ); 1753 do{ 1754 sqlite3ExprDelete(db, pItem->pExpr); 1755 sqlite3DbFree(db, pItem->zName); 1756 sqlite3DbFree(db, pItem->zSpan); 1757 pItem++; 1758 }while( --i>0 ); 1759 sqlite3DbFreeNN(db, pList); 1760 } 1761 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ 1762 if( pList ) exprListDeleteNN(db, pList); 1763 } 1764 1765 /* 1766 ** Return the bitwise-OR of all Expr.flags fields in the given 1767 ** ExprList. 1768 */ 1769 u32 sqlite3ExprListFlags(const ExprList *pList){ 1770 int i; 1771 u32 m = 0; 1772 assert( pList!=0 ); 1773 for(i=0; i<pList->nExpr; i++){ 1774 Expr *pExpr = pList->a[i].pExpr; 1775 assert( pExpr!=0 ); 1776 m |= pExpr->flags; 1777 } 1778 return m; 1779 } 1780 1781 /* 1782 ** This is a SELECT-node callback for the expression walker that 1783 ** always "fails". By "fail" in this case, we mean set 1784 ** pWalker->eCode to zero and abort. 1785 ** 1786 ** This callback is used by multiple expression walkers. 1787 */ 1788 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){ 1789 UNUSED_PARAMETER(NotUsed); 1790 pWalker->eCode = 0; 1791 return WRC_Abort; 1792 } 1793 1794 /* 1795 ** If the input expression is an ID with the name "true" or "false" 1796 ** then convert it into an TK_TRUEFALSE term. Return non-zero if 1797 ** the conversion happened, and zero if the expression is unaltered. 1798 */ 1799 int sqlite3ExprIdToTrueFalse(Expr *pExpr){ 1800 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING ); 1801 if( !ExprHasProperty(pExpr, EP_Quoted) 1802 && (sqlite3StrICmp(pExpr->u.zToken, "true")==0 1803 || sqlite3StrICmp(pExpr->u.zToken, "false")==0) 1804 ){ 1805 pExpr->op = TK_TRUEFALSE; 1806 ExprSetProperty(pExpr, pExpr->u.zToken[4]==0 ? EP_IsTrue : EP_IsFalse); 1807 return 1; 1808 } 1809 return 0; 1810 } 1811 1812 /* 1813 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE 1814 ** and 0 if it is FALSE. 1815 */ 1816 int sqlite3ExprTruthValue(const Expr *pExpr){ 1817 pExpr = sqlite3ExprSkipCollate((Expr*)pExpr); 1818 assert( pExpr->op==TK_TRUEFALSE ); 1819 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0 1820 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 ); 1821 return pExpr->u.zToken[4]==0; 1822 } 1823 1824 /* 1825 ** If pExpr is an AND or OR expression, try to simplify it by eliminating 1826 ** terms that are always true or false. Return the simplified expression. 1827 ** Or return the original expression if no simplification is possible. 1828 ** 1829 ** Examples: 1830 ** 1831 ** (x<10) AND true => (x<10) 1832 ** (x<10) AND false => false 1833 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22) 1834 ** (x<10) AND (y=22 OR true) => (x<10) 1835 ** (y=22) OR true => true 1836 */ 1837 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){ 1838 assert( pExpr!=0 ); 1839 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){ 1840 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight); 1841 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft); 1842 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){ 1843 pExpr = pExpr->op==TK_AND ? pRight : pLeft; 1844 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){ 1845 pExpr = pExpr->op==TK_AND ? pLeft : pRight; 1846 } 1847 } 1848 return pExpr; 1849 } 1850 1851 1852 /* 1853 ** These routines are Walker callbacks used to check expressions to 1854 ** see if they are "constant" for some definition of constant. The 1855 ** Walker.eCode value determines the type of "constant" we are looking 1856 ** for. 1857 ** 1858 ** These callback routines are used to implement the following: 1859 ** 1860 ** sqlite3ExprIsConstant() pWalker->eCode==1 1861 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 1862 ** sqlite3ExprIsTableConstant() pWalker->eCode==3 1863 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 1864 ** 1865 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression 1866 ** is found to not be a constant. 1867 ** 1868 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions 1869 ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing 1870 ** an existing schema and 4 when processing a new statement. A bound 1871 ** parameter raises an error for new statements, but is silently converted 1872 ** to NULL for existing schemas. This allows sqlite_master tables that 1873 ** contain a bound parameter because they were generated by older versions 1874 ** of SQLite to be parsed by newer versions of SQLite without raising a 1875 ** malformed schema error. 1876 */ 1877 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ 1878 1879 /* If pWalker->eCode is 2 then any term of the expression that comes from 1880 ** the ON or USING clauses of a left join disqualifies the expression 1881 ** from being considered constant. */ 1882 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){ 1883 pWalker->eCode = 0; 1884 return WRC_Abort; 1885 } 1886 1887 switch( pExpr->op ){ 1888 /* Consider functions to be constant if all their arguments are constant 1889 ** and either pWalker->eCode==4 or 5 or the function has the 1890 ** SQLITE_FUNC_CONST flag. */ 1891 case TK_FUNCTION: 1892 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){ 1893 return WRC_Continue; 1894 }else{ 1895 pWalker->eCode = 0; 1896 return WRC_Abort; 1897 } 1898 case TK_ID: 1899 /* Convert "true" or "false" in a DEFAULT clause into the 1900 ** appropriate TK_TRUEFALSE operator */ 1901 if( sqlite3ExprIdToTrueFalse(pExpr) ){ 1902 return WRC_Prune; 1903 } 1904 /* Fall thru */ 1905 case TK_COLUMN: 1906 case TK_AGG_FUNCTION: 1907 case TK_AGG_COLUMN: 1908 testcase( pExpr->op==TK_ID ); 1909 testcase( pExpr->op==TK_COLUMN ); 1910 testcase( pExpr->op==TK_AGG_FUNCTION ); 1911 testcase( pExpr->op==TK_AGG_COLUMN ); 1912 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){ 1913 return WRC_Continue; 1914 } 1915 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ 1916 return WRC_Continue; 1917 } 1918 /* Fall through */ 1919 case TK_IF_NULL_ROW: 1920 case TK_REGISTER: 1921 testcase( pExpr->op==TK_REGISTER ); 1922 testcase( pExpr->op==TK_IF_NULL_ROW ); 1923 pWalker->eCode = 0; 1924 return WRC_Abort; 1925 case TK_VARIABLE: 1926 if( pWalker->eCode==5 ){ 1927 /* Silently convert bound parameters that appear inside of CREATE 1928 ** statements into a NULL when parsing the CREATE statement text out 1929 ** of the sqlite_master table */ 1930 pExpr->op = TK_NULL; 1931 }else if( pWalker->eCode==4 ){ 1932 /* A bound parameter in a CREATE statement that originates from 1933 ** sqlite3_prepare() causes an error */ 1934 pWalker->eCode = 0; 1935 return WRC_Abort; 1936 } 1937 /* Fall through */ 1938 default: 1939 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */ 1940 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */ 1941 return WRC_Continue; 1942 } 1943 } 1944 static int exprIsConst(Expr *p, int initFlag, int iCur){ 1945 Walker w; 1946 w.eCode = initFlag; 1947 w.xExprCallback = exprNodeIsConstant; 1948 w.xSelectCallback = sqlite3SelectWalkFail; 1949 #ifdef SQLITE_DEBUG 1950 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 1951 #endif 1952 w.u.iCur = iCur; 1953 sqlite3WalkExpr(&w, p); 1954 return w.eCode; 1955 } 1956 1957 /* 1958 ** Walk an expression tree. Return non-zero if the expression is constant 1959 ** and 0 if it involves variables or function calls. 1960 ** 1961 ** For the purposes of this function, a double-quoted string (ex: "abc") 1962 ** is considered a variable but a single-quoted string (ex: 'abc') is 1963 ** a constant. 1964 */ 1965 int sqlite3ExprIsConstant(Expr *p){ 1966 return exprIsConst(p, 1, 0); 1967 } 1968 1969 /* 1970 ** Walk an expression tree. Return non-zero if 1971 ** 1972 ** (1) the expression is constant, and 1973 ** (2) the expression does originate in the ON or USING clause 1974 ** of a LEFT JOIN, and 1975 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN 1976 ** operands created by the constant propagation optimization. 1977 ** 1978 ** When this routine returns true, it indicates that the expression 1979 ** can be added to the pParse->pConstExpr list and evaluated once when 1980 ** the prepared statement starts up. See sqlite3ExprCodeAtInit(). 1981 */ 1982 int sqlite3ExprIsConstantNotJoin(Expr *p){ 1983 return exprIsConst(p, 2, 0); 1984 } 1985 1986 /* 1987 ** Walk an expression tree. Return non-zero if the expression is constant 1988 ** for any single row of the table with cursor iCur. In other words, the 1989 ** expression must not refer to any non-deterministic function nor any 1990 ** table other than iCur. 1991 */ 1992 int sqlite3ExprIsTableConstant(Expr *p, int iCur){ 1993 return exprIsConst(p, 3, iCur); 1994 } 1995 1996 1997 /* 1998 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy(). 1999 */ 2000 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){ 2001 ExprList *pGroupBy = pWalker->u.pGroupBy; 2002 int i; 2003 2004 /* Check if pExpr is identical to any GROUP BY term. If so, consider 2005 ** it constant. */ 2006 for(i=0; i<pGroupBy->nExpr; i++){ 2007 Expr *p = pGroupBy->a[i].pExpr; 2008 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){ 2009 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p); 2010 if( sqlite3IsBinary(pColl) ){ 2011 return WRC_Prune; 2012 } 2013 } 2014 } 2015 2016 /* Check if pExpr is a sub-select. If so, consider it variable. */ 2017 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 2018 pWalker->eCode = 0; 2019 return WRC_Abort; 2020 } 2021 2022 return exprNodeIsConstant(pWalker, pExpr); 2023 } 2024 2025 /* 2026 ** Walk the expression tree passed as the first argument. Return non-zero 2027 ** if the expression consists entirely of constants or copies of terms 2028 ** in pGroupBy that sort with the BINARY collation sequence. 2029 ** 2030 ** This routine is used to determine if a term of the HAVING clause can 2031 ** be promoted into the WHERE clause. In order for such a promotion to work, 2032 ** the value of the HAVING clause term must be the same for all members of 2033 ** a "group". The requirement that the GROUP BY term must be BINARY 2034 ** assumes that no other collating sequence will have a finer-grained 2035 ** grouping than binary. In other words (A=B COLLATE binary) implies 2036 ** A=B in every other collating sequence. The requirement that the 2037 ** GROUP BY be BINARY is stricter than necessary. It would also work 2038 ** to promote HAVING clauses that use the same alternative collating 2039 ** sequence as the GROUP BY term, but that is much harder to check, 2040 ** alternative collating sequences are uncommon, and this is only an 2041 ** optimization, so we take the easy way out and simply require the 2042 ** GROUP BY to use the BINARY collating sequence. 2043 */ 2044 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){ 2045 Walker w; 2046 w.eCode = 1; 2047 w.xExprCallback = exprNodeIsConstantOrGroupBy; 2048 w.xSelectCallback = 0; 2049 w.u.pGroupBy = pGroupBy; 2050 w.pParse = pParse; 2051 sqlite3WalkExpr(&w, p); 2052 return w.eCode; 2053 } 2054 2055 /* 2056 ** Walk an expression tree. Return non-zero if the expression is constant 2057 ** or a function call with constant arguments. Return and 0 if there 2058 ** are any variables. 2059 ** 2060 ** For the purposes of this function, a double-quoted string (ex: "abc") 2061 ** is considered a variable but a single-quoted string (ex: 'abc') is 2062 ** a constant. 2063 */ 2064 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ 2065 assert( isInit==0 || isInit==1 ); 2066 return exprIsConst(p, 4+isInit, 0); 2067 } 2068 2069 #ifdef SQLITE_ENABLE_CURSOR_HINTS 2070 /* 2071 ** Walk an expression tree. Return 1 if the expression contains a 2072 ** subquery of some kind. Return 0 if there are no subqueries. 2073 */ 2074 int sqlite3ExprContainsSubquery(Expr *p){ 2075 Walker w; 2076 w.eCode = 1; 2077 w.xExprCallback = sqlite3ExprWalkNoop; 2078 w.xSelectCallback = sqlite3SelectWalkFail; 2079 #ifdef SQLITE_DEBUG 2080 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 2081 #endif 2082 sqlite3WalkExpr(&w, p); 2083 return w.eCode==0; 2084 } 2085 #endif 2086 2087 /* 2088 ** If the expression p codes a constant integer that is small enough 2089 ** to fit in a 32-bit integer, return 1 and put the value of the integer 2090 ** in *pValue. If the expression is not an integer or if it is too big 2091 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. 2092 */ 2093 int sqlite3ExprIsInteger(Expr *p, int *pValue){ 2094 int rc = 0; 2095 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */ 2096 2097 /* If an expression is an integer literal that fits in a signed 32-bit 2098 ** integer, then the EP_IntValue flag will have already been set */ 2099 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 2100 || sqlite3GetInt32(p->u.zToken, &rc)==0 ); 2101 2102 if( p->flags & EP_IntValue ){ 2103 *pValue = p->u.iValue; 2104 return 1; 2105 } 2106 switch( p->op ){ 2107 case TK_UPLUS: { 2108 rc = sqlite3ExprIsInteger(p->pLeft, pValue); 2109 break; 2110 } 2111 case TK_UMINUS: { 2112 int v; 2113 if( sqlite3ExprIsInteger(p->pLeft, &v) ){ 2114 assert( v!=(-2147483647-1) ); 2115 *pValue = -v; 2116 rc = 1; 2117 } 2118 break; 2119 } 2120 default: break; 2121 } 2122 return rc; 2123 } 2124 2125 /* 2126 ** Return FALSE if there is no chance that the expression can be NULL. 2127 ** 2128 ** If the expression might be NULL or if the expression is too complex 2129 ** to tell return TRUE. 2130 ** 2131 ** This routine is used as an optimization, to skip OP_IsNull opcodes 2132 ** when we know that a value cannot be NULL. Hence, a false positive 2133 ** (returning TRUE when in fact the expression can never be NULL) might 2134 ** be a small performance hit but is otherwise harmless. On the other 2135 ** hand, a false negative (returning FALSE when the result could be NULL) 2136 ** will likely result in an incorrect answer. So when in doubt, return 2137 ** TRUE. 2138 */ 2139 int sqlite3ExprCanBeNull(const Expr *p){ 2140 u8 op; 2141 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ 2142 p = p->pLeft; 2143 } 2144 op = p->op; 2145 if( op==TK_REGISTER ) op = p->op2; 2146 switch( op ){ 2147 case TK_INTEGER: 2148 case TK_STRING: 2149 case TK_FLOAT: 2150 case TK_BLOB: 2151 return 0; 2152 case TK_COLUMN: 2153 return ExprHasProperty(p, EP_CanBeNull) || 2154 p->y.pTab==0 || /* Reference to column of index on expression */ 2155 (p->iColumn>=0 && p->y.pTab->aCol[p->iColumn].notNull==0); 2156 default: 2157 return 1; 2158 } 2159 } 2160 2161 /* 2162 ** Return TRUE if the given expression is a constant which would be 2163 ** unchanged by OP_Affinity with the affinity given in the second 2164 ** argument. 2165 ** 2166 ** This routine is used to determine if the OP_Affinity operation 2167 ** can be omitted. When in doubt return FALSE. A false negative 2168 ** is harmless. A false positive, however, can result in the wrong 2169 ** answer. 2170 */ 2171 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ 2172 u8 op; 2173 if( aff==SQLITE_AFF_BLOB ) return 1; 2174 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } 2175 op = p->op; 2176 if( op==TK_REGISTER ) op = p->op2; 2177 switch( op ){ 2178 case TK_INTEGER: { 2179 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC; 2180 } 2181 case TK_FLOAT: { 2182 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC; 2183 } 2184 case TK_STRING: { 2185 return aff==SQLITE_AFF_TEXT; 2186 } 2187 case TK_BLOB: { 2188 return 1; 2189 } 2190 case TK_COLUMN: { 2191 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ 2192 return p->iColumn<0 2193 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC); 2194 } 2195 default: { 2196 return 0; 2197 } 2198 } 2199 } 2200 2201 /* 2202 ** Return TRUE if the given string is a row-id column name. 2203 */ 2204 int sqlite3IsRowid(const char *z){ 2205 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; 2206 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; 2207 if( sqlite3StrICmp(z, "OID")==0 ) return 1; 2208 return 0; 2209 } 2210 2211 /* 2212 ** pX is the RHS of an IN operator. If pX is a SELECT statement 2213 ** that can be simplified to a direct table access, then return 2214 ** a pointer to the SELECT statement. If pX is not a SELECT statement, 2215 ** or if the SELECT statement needs to be manifested into a transient 2216 ** table, then return NULL. 2217 */ 2218 #ifndef SQLITE_OMIT_SUBQUERY 2219 static Select *isCandidateForInOpt(Expr *pX){ 2220 Select *p; 2221 SrcList *pSrc; 2222 ExprList *pEList; 2223 Table *pTab; 2224 int i; 2225 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */ 2226 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */ 2227 p = pX->x.pSelect; 2228 if( p->pPrior ) return 0; /* Not a compound SELECT */ 2229 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ 2230 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 2231 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 2232 return 0; /* No DISTINCT keyword and no aggregate functions */ 2233 } 2234 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ 2235 if( p->pLimit ) return 0; /* Has no LIMIT clause */ 2236 if( p->pWhere ) return 0; /* Has no WHERE clause */ 2237 pSrc = p->pSrc; 2238 assert( pSrc!=0 ); 2239 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ 2240 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ 2241 pTab = pSrc->a[0].pTab; 2242 assert( pTab!=0 ); 2243 assert( pTab->pSelect==0 ); /* FROM clause is not a view */ 2244 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ 2245 pEList = p->pEList; 2246 assert( pEList!=0 ); 2247 /* All SELECT results must be columns. */ 2248 for(i=0; i<pEList->nExpr; i++){ 2249 Expr *pRes = pEList->a[i].pExpr; 2250 if( pRes->op!=TK_COLUMN ) return 0; 2251 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */ 2252 } 2253 return p; 2254 } 2255 #endif /* SQLITE_OMIT_SUBQUERY */ 2256 2257 #ifndef SQLITE_OMIT_SUBQUERY 2258 /* 2259 ** Generate code that checks the left-most column of index table iCur to see if 2260 ** it contains any NULL entries. Cause the register at regHasNull to be set 2261 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull 2262 ** to be set to NULL if iCur contains one or more NULL values. 2263 */ 2264 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ 2265 int addr1; 2266 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); 2267 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); 2268 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); 2269 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); 2270 VdbeComment((v, "first_entry_in(%d)", iCur)); 2271 sqlite3VdbeJumpHere(v, addr1); 2272 } 2273 #endif 2274 2275 2276 #ifndef SQLITE_OMIT_SUBQUERY 2277 /* 2278 ** The argument is an IN operator with a list (not a subquery) on the 2279 ** right-hand side. Return TRUE if that list is constant. 2280 */ 2281 static int sqlite3InRhsIsConstant(Expr *pIn){ 2282 Expr *pLHS; 2283 int res; 2284 assert( !ExprHasProperty(pIn, EP_xIsSelect) ); 2285 pLHS = pIn->pLeft; 2286 pIn->pLeft = 0; 2287 res = sqlite3ExprIsConstant(pIn); 2288 pIn->pLeft = pLHS; 2289 return res; 2290 } 2291 #endif 2292 2293 /* 2294 ** This function is used by the implementation of the IN (...) operator. 2295 ** The pX parameter is the expression on the RHS of the IN operator, which 2296 ** might be either a list of expressions or a subquery. 2297 ** 2298 ** The job of this routine is to find or create a b-tree object that can 2299 ** be used either to test for membership in the RHS set or to iterate through 2300 ** all members of the RHS set, skipping duplicates. 2301 ** 2302 ** A cursor is opened on the b-tree object that is the RHS of the IN operator 2303 ** and pX->iTable is set to the index of that cursor. 2304 ** 2305 ** The returned value of this function indicates the b-tree type, as follows: 2306 ** 2307 ** IN_INDEX_ROWID - The cursor was opened on a database table. 2308 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. 2309 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. 2310 ** IN_INDEX_EPH - The cursor was opened on a specially created and 2311 ** populated epheremal table. 2312 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be 2313 ** implemented as a sequence of comparisons. 2314 ** 2315 ** An existing b-tree might be used if the RHS expression pX is a simple 2316 ** subquery such as: 2317 ** 2318 ** SELECT <column1>, <column2>... FROM <table> 2319 ** 2320 ** If the RHS of the IN operator is a list or a more complex subquery, then 2321 ** an ephemeral table might need to be generated from the RHS and then 2322 ** pX->iTable made to point to the ephemeral table instead of an 2323 ** existing table. 2324 ** 2325 ** The inFlags parameter must contain, at a minimum, one of the bits 2326 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains 2327 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast 2328 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will 2329 ** be used to loop over all values of the RHS of the IN operator. 2330 ** 2331 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate 2332 ** through the set members) then the b-tree must not contain duplicates. 2333 ** An epheremal table will be created unless the selected columns are guaranteed 2334 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to 2335 ** a UNIQUE constraint or index. 2336 ** 2337 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 2338 ** for fast set membership tests) then an epheremal table must 2339 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an 2340 ** index can be found with the specified <columns> as its left-most. 2341 ** 2342 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and 2343 ** if the RHS of the IN operator is a list (not a subquery) then this 2344 ** routine might decide that creating an ephemeral b-tree for membership 2345 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the 2346 ** calling routine should implement the IN operator using a sequence 2347 ** of Eq or Ne comparison operations. 2348 ** 2349 ** When the b-tree is being used for membership tests, the calling function 2350 ** might need to know whether or not the RHS side of the IN operator 2351 ** contains a NULL. If prRhsHasNull is not a NULL pointer and 2352 ** if there is any chance that the (...) might contain a NULL value at 2353 ** runtime, then a register is allocated and the register number written 2354 ** to *prRhsHasNull. If there is no chance that the (...) contains a 2355 ** NULL value, then *prRhsHasNull is left unchanged. 2356 ** 2357 ** If a register is allocated and its location stored in *prRhsHasNull, then 2358 ** the value in that register will be NULL if the b-tree contains one or more 2359 ** NULL values, and it will be some non-NULL value if the b-tree contains no 2360 ** NULL values. 2361 ** 2362 ** If the aiMap parameter is not NULL, it must point to an array containing 2363 ** one element for each column returned by the SELECT statement on the RHS 2364 ** of the IN(...) operator. The i'th entry of the array is populated with the 2365 ** offset of the index column that matches the i'th column returned by the 2366 ** SELECT. For example, if the expression and selected index are: 2367 ** 2368 ** (?,?,?) IN (SELECT a, b, c FROM t1) 2369 ** CREATE INDEX i1 ON t1(b, c, a); 2370 ** 2371 ** then aiMap[] is populated with {2, 0, 1}. 2372 */ 2373 #ifndef SQLITE_OMIT_SUBQUERY 2374 int sqlite3FindInIndex( 2375 Parse *pParse, /* Parsing context */ 2376 Expr *pX, /* The right-hand side (RHS) of the IN operator */ 2377 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */ 2378 int *prRhsHasNull, /* Register holding NULL status. See notes */ 2379 int *aiMap, /* Mapping from Index fields to RHS fields */ 2380 int *piTab /* OUT: index to use */ 2381 ){ 2382 Select *p; /* SELECT to the right of IN operator */ 2383 int eType = 0; /* Type of RHS table. IN_INDEX_* */ 2384 int iTab = pParse->nTab++; /* Cursor of the RHS table */ 2385 int mustBeUnique; /* True if RHS must be unique */ 2386 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ 2387 2388 assert( pX->op==TK_IN ); 2389 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0; 2390 2391 /* If the RHS of this IN(...) operator is a SELECT, and if it matters 2392 ** whether or not the SELECT result contains NULL values, check whether 2393 ** or not NULL is actually possible (it may not be, for example, due 2394 ** to NOT NULL constraints in the schema). If no NULL values are possible, 2395 ** set prRhsHasNull to 0 before continuing. */ 2396 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){ 2397 int i; 2398 ExprList *pEList = pX->x.pSelect->pEList; 2399 for(i=0; i<pEList->nExpr; i++){ 2400 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; 2401 } 2402 if( i==pEList->nExpr ){ 2403 prRhsHasNull = 0; 2404 } 2405 } 2406 2407 /* Check to see if an existing table or index can be used to 2408 ** satisfy the query. This is preferable to generating a new 2409 ** ephemeral table. */ 2410 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){ 2411 sqlite3 *db = pParse->db; /* Database connection */ 2412 Table *pTab; /* Table <table>. */ 2413 i16 iDb; /* Database idx for pTab */ 2414 ExprList *pEList = p->pEList; 2415 int nExpr = pEList->nExpr; 2416 2417 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ 2418 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ 2419 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ 2420 pTab = p->pSrc->a[0].pTab; 2421 2422 /* Code an OP_Transaction and OP_TableLock for <table>. */ 2423 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2424 sqlite3CodeVerifySchema(pParse, iDb); 2425 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 2426 2427 assert(v); /* sqlite3GetVdbe() has always been previously called */ 2428 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){ 2429 /* The "x IN (SELECT rowid FROM table)" case */ 2430 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); 2431 VdbeCoverage(v); 2432 2433 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 2434 eType = IN_INDEX_ROWID; 2435 ExplainQueryPlan((pParse, 0, 2436 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName)); 2437 sqlite3VdbeJumpHere(v, iAddr); 2438 }else{ 2439 Index *pIdx; /* Iterator variable */ 2440 int affinity_ok = 1; 2441 int i; 2442 2443 /* Check that the affinity that will be used to perform each 2444 ** comparison is the same as the affinity of each column in table 2445 ** on the RHS of the IN operator. If it not, it is not possible to 2446 ** use any index of the RHS table. */ 2447 for(i=0; i<nExpr && affinity_ok; i++){ 2448 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); 2449 int iCol = pEList->a[i].pExpr->iColumn; 2450 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ 2451 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff); 2452 testcase( cmpaff==SQLITE_AFF_BLOB ); 2453 testcase( cmpaff==SQLITE_AFF_TEXT ); 2454 switch( cmpaff ){ 2455 case SQLITE_AFF_BLOB: 2456 break; 2457 case SQLITE_AFF_TEXT: 2458 /* sqlite3CompareAffinity() only returns TEXT if one side or the 2459 ** other has no affinity and the other side is TEXT. Hence, 2460 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT 2461 ** and for the term on the LHS of the IN to have no affinity. */ 2462 assert( idxaff==SQLITE_AFF_TEXT ); 2463 break; 2464 default: 2465 affinity_ok = sqlite3IsNumericAffinity(idxaff); 2466 } 2467 } 2468 2469 if( affinity_ok ){ 2470 /* Search for an existing index that will work for this IN operator */ 2471 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){ 2472 Bitmask colUsed; /* Columns of the index used */ 2473 Bitmask mCol; /* Mask for the current column */ 2474 if( pIdx->nColumn<nExpr ) continue; 2475 if( pIdx->pPartIdxWhere!=0 ) continue; 2476 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute 2477 ** BITMASK(nExpr) without overflowing */ 2478 testcase( pIdx->nColumn==BMS-2 ); 2479 testcase( pIdx->nColumn==BMS-1 ); 2480 if( pIdx->nColumn>=BMS-1 ) continue; 2481 if( mustBeUnique ){ 2482 if( pIdx->nKeyCol>nExpr 2483 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx)) 2484 ){ 2485 continue; /* This index is not unique over the IN RHS columns */ 2486 } 2487 } 2488 2489 colUsed = 0; /* Columns of index used so far */ 2490 for(i=0; i<nExpr; i++){ 2491 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); 2492 Expr *pRhs = pEList->a[i].pExpr; 2493 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); 2494 int j; 2495 2496 assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr ); 2497 for(j=0; j<nExpr; j++){ 2498 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue; 2499 assert( pIdx->azColl[j] ); 2500 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ 2501 continue; 2502 } 2503 break; 2504 } 2505 if( j==nExpr ) break; 2506 mCol = MASKBIT(j); 2507 if( mCol & colUsed ) break; /* Each column used only once */ 2508 colUsed |= mCol; 2509 if( aiMap ) aiMap[i] = j; 2510 } 2511 2512 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) ); 2513 if( colUsed==(MASKBIT(nExpr)-1) ){ 2514 /* If we reach this point, that means the index pIdx is usable */ 2515 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 2516 ExplainQueryPlan((pParse, 0, 2517 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName)); 2518 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); 2519 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 2520 VdbeComment((v, "%s", pIdx->zName)); 2521 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); 2522 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; 2523 2524 if( prRhsHasNull ){ 2525 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 2526 i64 mask = (1<<nExpr)-1; 2527 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, 2528 iTab, 0, 0, (u8*)&mask, P4_INT64); 2529 #endif 2530 *prRhsHasNull = ++pParse->nMem; 2531 if( nExpr==1 ){ 2532 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); 2533 } 2534 } 2535 sqlite3VdbeJumpHere(v, iAddr); 2536 } 2537 } /* End loop over indexes */ 2538 } /* End if( affinity_ok ) */ 2539 } /* End if not an rowid index */ 2540 } /* End attempt to optimize using an index */ 2541 2542 /* If no preexisting index is available for the IN clause 2543 ** and IN_INDEX_NOOP is an allowed reply 2544 ** and the RHS of the IN operator is a list, not a subquery 2545 ** and the RHS is not constant or has two or fewer terms, 2546 ** then it is not worth creating an ephemeral table to evaluate 2547 ** the IN operator so return IN_INDEX_NOOP. 2548 */ 2549 if( eType==0 2550 && (inFlags & IN_INDEX_NOOP_OK) 2551 && !ExprHasProperty(pX, EP_xIsSelect) 2552 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2) 2553 ){ 2554 eType = IN_INDEX_NOOP; 2555 } 2556 2557 if( eType==0 ){ 2558 /* Could not find an existing table or index to use as the RHS b-tree. 2559 ** We will have to generate an ephemeral table to do the job. 2560 */ 2561 u32 savedNQueryLoop = pParse->nQueryLoop; 2562 int rMayHaveNull = 0; 2563 eType = IN_INDEX_EPH; 2564 if( inFlags & IN_INDEX_LOOP ){ 2565 pParse->nQueryLoop = 0; 2566 }else if( prRhsHasNull ){ 2567 *prRhsHasNull = rMayHaveNull = ++pParse->nMem; 2568 } 2569 assert( pX->op==TK_IN ); 2570 sqlite3CodeRhsOfIN(pParse, pX, iTab); 2571 if( rMayHaveNull ){ 2572 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull); 2573 } 2574 pParse->nQueryLoop = savedNQueryLoop; 2575 } 2576 2577 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){ 2578 int i, n; 2579 n = sqlite3ExprVectorSize(pX->pLeft); 2580 for(i=0; i<n; i++) aiMap[i] = i; 2581 } 2582 *piTab = iTab; 2583 return eType; 2584 } 2585 #endif 2586 2587 #ifndef SQLITE_OMIT_SUBQUERY 2588 /* 2589 ** Argument pExpr is an (?, ?...) IN(...) expression. This 2590 ** function allocates and returns a nul-terminated string containing 2591 ** the affinities to be used for each column of the comparison. 2592 ** 2593 ** It is the responsibility of the caller to ensure that the returned 2594 ** string is eventually freed using sqlite3DbFree(). 2595 */ 2596 static char *exprINAffinity(Parse *pParse, Expr *pExpr){ 2597 Expr *pLeft = pExpr->pLeft; 2598 int nVal = sqlite3ExprVectorSize(pLeft); 2599 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0; 2600 char *zRet; 2601 2602 assert( pExpr->op==TK_IN ); 2603 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1); 2604 if( zRet ){ 2605 int i; 2606 for(i=0; i<nVal; i++){ 2607 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i); 2608 char a = sqlite3ExprAffinity(pA); 2609 if( pSelect ){ 2610 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a); 2611 }else{ 2612 zRet[i] = a; 2613 } 2614 } 2615 zRet[nVal] = '\0'; 2616 } 2617 return zRet; 2618 } 2619 #endif 2620 2621 #ifndef SQLITE_OMIT_SUBQUERY 2622 /* 2623 ** Load the Parse object passed as the first argument with an error 2624 ** message of the form: 2625 ** 2626 ** "sub-select returns N columns - expected M" 2627 */ 2628 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ 2629 const char *zFmt = "sub-select returns %d columns - expected %d"; 2630 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); 2631 } 2632 #endif 2633 2634 /* 2635 ** Expression pExpr is a vector that has been used in a context where 2636 ** it is not permitted. If pExpr is a sub-select vector, this routine 2637 ** loads the Parse object with a message of the form: 2638 ** 2639 ** "sub-select returns N columns - expected 1" 2640 ** 2641 ** Or, if it is a regular scalar vector: 2642 ** 2643 ** "row value misused" 2644 */ 2645 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){ 2646 #ifndef SQLITE_OMIT_SUBQUERY 2647 if( pExpr->flags & EP_xIsSelect ){ 2648 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1); 2649 }else 2650 #endif 2651 { 2652 sqlite3ErrorMsg(pParse, "row value misused"); 2653 } 2654 } 2655 2656 #ifndef SQLITE_OMIT_SUBQUERY 2657 /* 2658 ** Generate code that will construct an ephemeral table containing all terms 2659 ** in the RHS of an IN operator. The IN operator can be in either of two 2660 ** forms: 2661 ** 2662 ** x IN (4,5,11) -- IN operator with list on right-hand side 2663 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right 2664 ** 2665 ** The pExpr parameter is the IN operator. The cursor number for the 2666 ** constructed ephermeral table is returned. The first time the ephemeral 2667 ** table is computed, the cursor number is also stored in pExpr->iTable, 2668 ** however the cursor number returned might not be the same, as it might 2669 ** have been duplicated using OP_OpenDup. 2670 ** 2671 ** If the LHS expression ("x" in the examples) is a column value, or 2672 ** the SELECT statement returns a column value, then the affinity of that 2673 ** column is used to build the index keys. If both 'x' and the 2674 ** SELECT... statement are columns, then numeric affinity is used 2675 ** if either column has NUMERIC or INTEGER affinity. If neither 2676 ** 'x' nor the SELECT... statement are columns, then numeric affinity 2677 ** is used. 2678 */ 2679 void sqlite3CodeRhsOfIN( 2680 Parse *pParse, /* Parsing context */ 2681 Expr *pExpr, /* The IN operator */ 2682 int iTab /* Use this cursor number */ 2683 ){ 2684 int addrOnce = 0; /* Address of the OP_Once instruction at top */ 2685 int addr; /* Address of OP_OpenEphemeral instruction */ 2686 Expr *pLeft; /* the LHS of the IN operator */ 2687 KeyInfo *pKeyInfo = 0; /* Key information */ 2688 int nVal; /* Size of vector pLeft */ 2689 Vdbe *v; /* The prepared statement under construction */ 2690 2691 v = pParse->pVdbe; 2692 assert( v!=0 ); 2693 2694 /* The evaluation of the IN must be repeated every time it 2695 ** is encountered if any of the following is true: 2696 ** 2697 ** * The right-hand side is a correlated subquery 2698 ** * The right-hand side is an expression list containing variables 2699 ** * We are inside a trigger 2700 ** 2701 ** If all of the above are false, then we can compute the RHS just once 2702 ** and reuse it many names. 2703 */ 2704 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){ 2705 /* Reuse of the RHS is allowed */ 2706 /* If this routine has already been coded, but the previous code 2707 ** might not have been invoked yet, so invoke it now as a subroutine. 2708 */ 2709 if( ExprHasProperty(pExpr, EP_Subrtn) ){ 2710 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 2711 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 2712 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d", 2713 pExpr->x.pSelect->selId)); 2714 } 2715 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, 2716 pExpr->y.sub.iAddr); 2717 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable); 2718 sqlite3VdbeJumpHere(v, addrOnce); 2719 return; 2720 } 2721 2722 /* Begin coding the subroutine */ 2723 ExprSetProperty(pExpr, EP_Subrtn); 2724 pExpr->y.sub.regReturn = ++pParse->nMem; 2725 pExpr->y.sub.iAddr = 2726 sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1; 2727 VdbeComment((v, "return address")); 2728 2729 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 2730 } 2731 2732 /* Check to see if this is a vector IN operator */ 2733 pLeft = pExpr->pLeft; 2734 nVal = sqlite3ExprVectorSize(pLeft); 2735 2736 /* Construct the ephemeral table that will contain the content of 2737 ** RHS of the IN operator. 2738 */ 2739 pExpr->iTable = iTab; 2740 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal); 2741 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS 2742 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 2743 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId)); 2744 }else{ 2745 VdbeComment((v, "RHS of IN operator")); 2746 } 2747 #endif 2748 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1); 2749 2750 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 2751 /* Case 1: expr IN (SELECT ...) 2752 ** 2753 ** Generate code to write the results of the select into the temporary 2754 ** table allocated and opened above. 2755 */ 2756 Select *pSelect = pExpr->x.pSelect; 2757 ExprList *pEList = pSelect->pEList; 2758 2759 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d", 2760 addrOnce?"":"CORRELATED ", pSelect->selId 2761 )); 2762 /* If the LHS and RHS of the IN operator do not match, that 2763 ** error will have been caught long before we reach this point. */ 2764 if( ALWAYS(pEList->nExpr==nVal) ){ 2765 SelectDest dest; 2766 int i; 2767 sqlite3SelectDestInit(&dest, SRT_Set, iTab); 2768 dest.zAffSdst = exprINAffinity(pParse, pExpr); 2769 pSelect->iLimit = 0; 2770 testcase( pSelect->selFlags & SF_Distinct ); 2771 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ 2772 if( sqlite3Select(pParse, pSelect, &dest) ){ 2773 sqlite3DbFree(pParse->db, dest.zAffSdst); 2774 sqlite3KeyInfoUnref(pKeyInfo); 2775 return; 2776 } 2777 sqlite3DbFree(pParse->db, dest.zAffSdst); 2778 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ 2779 assert( pEList!=0 ); 2780 assert( pEList->nExpr>0 ); 2781 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); 2782 for(i=0; i<nVal; i++){ 2783 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i); 2784 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq( 2785 pParse, p, pEList->a[i].pExpr 2786 ); 2787 } 2788 } 2789 }else if( ALWAYS(pExpr->x.pList!=0) ){ 2790 /* Case 2: expr IN (exprlist) 2791 ** 2792 ** For each expression, build an index key from the evaluation and 2793 ** store it in the temporary table. If <expr> is a column, then use 2794 ** that columns affinity when building index keys. If <expr> is not 2795 ** a column, use numeric affinity. 2796 */ 2797 char affinity; /* Affinity of the LHS of the IN */ 2798 int i; 2799 ExprList *pList = pExpr->x.pList; 2800 struct ExprList_item *pItem; 2801 int r1, r2, r3; 2802 affinity = sqlite3ExprAffinity(pLeft); 2803 if( !affinity ){ 2804 affinity = SQLITE_AFF_BLOB; 2805 } 2806 if( pKeyInfo ){ 2807 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); 2808 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 2809 } 2810 2811 /* Loop through each expression in <exprlist>. */ 2812 r1 = sqlite3GetTempReg(pParse); 2813 r2 = sqlite3GetTempReg(pParse); 2814 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ 2815 Expr *pE2 = pItem->pExpr; 2816 2817 /* If the expression is not constant then we will need to 2818 ** disable the test that was generated above that makes sure 2819 ** this code only executes once. Because for a non-constant 2820 ** expression we need to rerun this code each time. 2821 */ 2822 if( addrOnce && !sqlite3ExprIsConstant(pE2) ){ 2823 sqlite3VdbeChangeToNoop(v, addrOnce); 2824 ExprClearProperty(pExpr, EP_Subrtn); 2825 addrOnce = 0; 2826 } 2827 2828 /* Evaluate the expression and insert it into the temp table */ 2829 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); 2830 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); 2831 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r3, 1); 2832 } 2833 sqlite3ReleaseTempReg(pParse, r1); 2834 sqlite3ReleaseTempReg(pParse, r2); 2835 } 2836 if( pKeyInfo ){ 2837 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); 2838 } 2839 if( addrOnce ){ 2840 sqlite3VdbeJumpHere(v, addrOnce); 2841 /* Subroutine return */ 2842 sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn); 2843 sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1); 2844 } 2845 } 2846 #endif /* SQLITE_OMIT_SUBQUERY */ 2847 2848 /* 2849 ** Generate code for scalar subqueries used as a subquery expression 2850 ** or EXISTS operator: 2851 ** 2852 ** (SELECT a FROM b) -- subquery 2853 ** EXISTS (SELECT a FROM b) -- EXISTS subquery 2854 ** 2855 ** The pExpr parameter is the SELECT or EXISTS operator to be coded. 2856 ** 2857 ** The register that holds the result. For a multi-column SELECT, 2858 ** the result is stored in a contiguous array of registers and the 2859 ** return value is the register of the left-most result column. 2860 ** Return 0 if an error occurs. 2861 */ 2862 #ifndef SQLITE_OMIT_SUBQUERY 2863 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ 2864 int addrOnce = 0; /* Address of OP_Once at top of subroutine */ 2865 int rReg = 0; /* Register storing resulting */ 2866 Select *pSel; /* SELECT statement to encode */ 2867 SelectDest dest; /* How to deal with SELECT result */ 2868 int nReg; /* Registers to allocate */ 2869 Expr *pLimit; /* New limit expression */ 2870 2871 Vdbe *v = pParse->pVdbe; 2872 assert( v!=0 ); 2873 testcase( pExpr->op==TK_EXISTS ); 2874 testcase( pExpr->op==TK_SELECT ); 2875 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); 2876 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 2877 pSel = pExpr->x.pSelect; 2878 2879 /* The evaluation of the EXISTS/SELECT must be repeated every time it 2880 ** is encountered if any of the following is true: 2881 ** 2882 ** * The right-hand side is a correlated subquery 2883 ** * The right-hand side is an expression list containing variables 2884 ** * We are inside a trigger 2885 ** 2886 ** If all of the above are false, then we can run this code just once 2887 ** save the results, and reuse the same result on subsequent invocations. 2888 */ 2889 if( !ExprHasProperty(pExpr, EP_VarSelect) ){ 2890 /* If this routine has already been coded, then invoke it as a 2891 ** subroutine. */ 2892 if( ExprHasProperty(pExpr, EP_Subrtn) ){ 2893 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId)); 2894 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, 2895 pExpr->y.sub.iAddr); 2896 return pExpr->iTable; 2897 } 2898 2899 /* Begin coding the subroutine */ 2900 ExprSetProperty(pExpr, EP_Subrtn); 2901 pExpr->y.sub.regReturn = ++pParse->nMem; 2902 pExpr->y.sub.iAddr = 2903 sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1; 2904 VdbeComment((v, "return address")); 2905 2906 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 2907 } 2908 2909 /* For a SELECT, generate code to put the values for all columns of 2910 ** the first row into an array of registers and return the index of 2911 ** the first register. 2912 ** 2913 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) 2914 ** into a register and return that register number. 2915 ** 2916 ** In both cases, the query is augmented with "LIMIT 1". Any 2917 ** preexisting limit is discarded in place of the new LIMIT 1. 2918 */ 2919 ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d", 2920 addrOnce?"":"CORRELATED ", pSel->selId)); 2921 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; 2922 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1); 2923 pParse->nMem += nReg; 2924 if( pExpr->op==TK_SELECT ){ 2925 dest.eDest = SRT_Mem; 2926 dest.iSdst = dest.iSDParm; 2927 dest.nSdst = nReg; 2928 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); 2929 VdbeComment((v, "Init subquery result")); 2930 }else{ 2931 dest.eDest = SRT_Exists; 2932 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); 2933 VdbeComment((v, "Init EXISTS result")); 2934 } 2935 pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0); 2936 if( pSel->pLimit ){ 2937 sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft); 2938 pSel->pLimit->pLeft = pLimit; 2939 }else{ 2940 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0); 2941 } 2942 pSel->iLimit = 0; 2943 if( sqlite3Select(pParse, pSel, &dest) ){ 2944 return 0; 2945 } 2946 pExpr->iTable = rReg = dest.iSDParm; 2947 ExprSetVVAProperty(pExpr, EP_NoReduce); 2948 if( addrOnce ){ 2949 sqlite3VdbeJumpHere(v, addrOnce); 2950 2951 /* Subroutine return */ 2952 sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn); 2953 sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1); 2954 } 2955 2956 return rReg; 2957 } 2958 #endif /* SQLITE_OMIT_SUBQUERY */ 2959 2960 #ifndef SQLITE_OMIT_SUBQUERY 2961 /* 2962 ** Expr pIn is an IN(...) expression. This function checks that the 2963 ** sub-select on the RHS of the IN() operator has the same number of 2964 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not 2965 ** a sub-query, that the LHS is a vector of size 1. 2966 */ 2967 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ 2968 int nVector = sqlite3ExprVectorSize(pIn->pLeft); 2969 if( (pIn->flags & EP_xIsSelect) ){ 2970 if( nVector!=pIn->x.pSelect->pEList->nExpr ){ 2971 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); 2972 return 1; 2973 } 2974 }else if( nVector!=1 ){ 2975 sqlite3VectorErrorMsg(pParse, pIn->pLeft); 2976 return 1; 2977 } 2978 return 0; 2979 } 2980 #endif 2981 2982 #ifndef SQLITE_OMIT_SUBQUERY 2983 /* 2984 ** Generate code for an IN expression. 2985 ** 2986 ** x IN (SELECT ...) 2987 ** x IN (value, value, ...) 2988 ** 2989 ** The left-hand side (LHS) is a scalar or vector expression. The 2990 ** right-hand side (RHS) is an array of zero or more scalar values, or a 2991 ** subquery. If the RHS is a subquery, the number of result columns must 2992 ** match the number of columns in the vector on the LHS. If the RHS is 2993 ** a list of values, the LHS must be a scalar. 2994 ** 2995 ** The IN operator is true if the LHS value is contained within the RHS. 2996 ** The result is false if the LHS is definitely not in the RHS. The 2997 ** result is NULL if the presence of the LHS in the RHS cannot be 2998 ** determined due to NULLs. 2999 ** 3000 ** This routine generates code that jumps to destIfFalse if the LHS is not 3001 ** contained within the RHS. If due to NULLs we cannot determine if the LHS 3002 ** is contained in the RHS then jump to destIfNull. If the LHS is contained 3003 ** within the RHS then fall through. 3004 ** 3005 ** See the separate in-operator.md documentation file in the canonical 3006 ** SQLite source tree for additional information. 3007 */ 3008 static void sqlite3ExprCodeIN( 3009 Parse *pParse, /* Parsing and code generating context */ 3010 Expr *pExpr, /* The IN expression */ 3011 int destIfFalse, /* Jump here if LHS is not contained in the RHS */ 3012 int destIfNull /* Jump here if the results are unknown due to NULLs */ 3013 ){ 3014 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ 3015 int eType; /* Type of the RHS */ 3016 int rLhs; /* Register(s) holding the LHS values */ 3017 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */ 3018 Vdbe *v; /* Statement under construction */ 3019 int *aiMap = 0; /* Map from vector field to index column */ 3020 char *zAff = 0; /* Affinity string for comparisons */ 3021 int nVector; /* Size of vectors for this IN operator */ 3022 int iDummy; /* Dummy parameter to exprCodeVector() */ 3023 Expr *pLeft; /* The LHS of the IN operator */ 3024 int i; /* loop counter */ 3025 int destStep2; /* Where to jump when NULLs seen in step 2 */ 3026 int destStep6 = 0; /* Start of code for Step 6 */ 3027 int addrTruthOp; /* Address of opcode that determines the IN is true */ 3028 int destNotNull; /* Jump here if a comparison is not true in step 6 */ 3029 int addrTop; /* Top of the step-6 loop */ 3030 int iTab = 0; /* Index to use */ 3031 3032 pLeft = pExpr->pLeft; 3033 if( sqlite3ExprCheckIN(pParse, pExpr) ) return; 3034 zAff = exprINAffinity(pParse, pExpr); 3035 nVector = sqlite3ExprVectorSize(pExpr->pLeft); 3036 aiMap = (int*)sqlite3DbMallocZero( 3037 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1 3038 ); 3039 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; 3040 3041 /* Attempt to compute the RHS. After this step, if anything other than 3042 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab 3043 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned, 3044 ** the RHS has not yet been coded. */ 3045 v = pParse->pVdbe; 3046 assert( v!=0 ); /* OOM detected prior to this routine */ 3047 VdbeNoopComment((v, "begin IN expr")); 3048 eType = sqlite3FindInIndex(pParse, pExpr, 3049 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK, 3050 destIfFalse==destIfNull ? 0 : &rRhsHasNull, 3051 aiMap, &iTab); 3052 3053 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH 3054 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC 3055 ); 3056 #ifdef SQLITE_DEBUG 3057 /* Confirm that aiMap[] contains nVector integer values between 0 and 3058 ** nVector-1. */ 3059 for(i=0; i<nVector; i++){ 3060 int j, cnt; 3061 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++; 3062 assert( cnt==1 ); 3063 } 3064 #endif 3065 3066 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a 3067 ** vector, then it is stored in an array of nVector registers starting 3068 ** at r1. 3069 ** 3070 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector 3071 ** so that the fields are in the same order as an existing index. The 3072 ** aiMap[] array contains a mapping from the original LHS field order to 3073 ** the field order that matches the RHS index. 3074 */ 3075 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); 3076 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */ 3077 if( i==nVector ){ 3078 /* LHS fields are not reordered */ 3079 rLhs = rLhsOrig; 3080 }else{ 3081 /* Need to reorder the LHS fields according to aiMap */ 3082 rLhs = sqlite3GetTempRange(pParse, nVector); 3083 for(i=0; i<nVector; i++){ 3084 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0); 3085 } 3086 } 3087 3088 /* If sqlite3FindInIndex() did not find or create an index that is 3089 ** suitable for evaluating the IN operator, then evaluate using a 3090 ** sequence of comparisons. 3091 ** 3092 ** This is step (1) in the in-operator.md optimized algorithm. 3093 */ 3094 if( eType==IN_INDEX_NOOP ){ 3095 ExprList *pList = pExpr->x.pList; 3096 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 3097 int labelOk = sqlite3VdbeMakeLabel(pParse); 3098 int r2, regToFree; 3099 int regCkNull = 0; 3100 int ii; 3101 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 3102 if( destIfNull!=destIfFalse ){ 3103 regCkNull = sqlite3GetTempReg(pParse); 3104 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); 3105 } 3106 for(ii=0; ii<pList->nExpr; ii++){ 3107 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree); 3108 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ 3109 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); 3110 } 3111 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){ 3112 sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2, 3113 (void*)pColl, P4_COLLSEQ); 3114 VdbeCoverageIf(v, ii<pList->nExpr-1); 3115 VdbeCoverageIf(v, ii==pList->nExpr-1); 3116 sqlite3VdbeChangeP5(v, zAff[0]); 3117 }else{ 3118 assert( destIfNull==destIfFalse ); 3119 sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2, 3120 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v); 3121 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); 3122 } 3123 sqlite3ReleaseTempReg(pParse, regToFree); 3124 } 3125 if( regCkNull ){ 3126 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); 3127 sqlite3VdbeGoto(v, destIfFalse); 3128 } 3129 sqlite3VdbeResolveLabel(v, labelOk); 3130 sqlite3ReleaseTempReg(pParse, regCkNull); 3131 goto sqlite3ExprCodeIN_finished; 3132 } 3133 3134 /* Step 2: Check to see if the LHS contains any NULL columns. If the 3135 ** LHS does contain NULLs then the result must be either FALSE or NULL. 3136 ** We will then skip the binary search of the RHS. 3137 */ 3138 if( destIfNull==destIfFalse ){ 3139 destStep2 = destIfFalse; 3140 }else{ 3141 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse); 3142 } 3143 for(i=0; i<nVector; i++){ 3144 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i); 3145 if( sqlite3ExprCanBeNull(p) ){ 3146 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); 3147 VdbeCoverage(v); 3148 } 3149 } 3150 3151 /* Step 3. The LHS is now known to be non-NULL. Do the binary search 3152 ** of the RHS using the LHS as a probe. If found, the result is 3153 ** true. 3154 */ 3155 if( eType==IN_INDEX_ROWID ){ 3156 /* In this case, the RHS is the ROWID of table b-tree and so we also 3157 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 3158 ** into a single opcode. */ 3159 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs); 3160 VdbeCoverage(v); 3161 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ 3162 }else{ 3163 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); 3164 if( destIfFalse==destIfNull ){ 3165 /* Combine Step 3 and Step 5 into a single opcode */ 3166 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse, 3167 rLhs, nVector); VdbeCoverage(v); 3168 goto sqlite3ExprCodeIN_finished; 3169 } 3170 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */ 3171 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0, 3172 rLhs, nVector); VdbeCoverage(v); 3173 } 3174 3175 /* Step 4. If the RHS is known to be non-NULL and we did not find 3176 ** an match on the search above, then the result must be FALSE. 3177 */ 3178 if( rRhsHasNull && nVector==1 ){ 3179 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); 3180 VdbeCoverage(v); 3181 } 3182 3183 /* Step 5. If we do not care about the difference between NULL and 3184 ** FALSE, then just return false. 3185 */ 3186 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse); 3187 3188 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS. 3189 ** If any comparison is NULL, then the result is NULL. If all 3190 ** comparisons are FALSE then the final result is FALSE. 3191 ** 3192 ** For a scalar LHS, it is sufficient to check just the first row 3193 ** of the RHS. 3194 */ 3195 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); 3196 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse); 3197 VdbeCoverage(v); 3198 if( nVector>1 ){ 3199 destNotNull = sqlite3VdbeMakeLabel(pParse); 3200 }else{ 3201 /* For nVector==1, combine steps 6 and 7 by immediately returning 3202 ** FALSE if the first comparison is not NULL */ 3203 destNotNull = destIfFalse; 3204 } 3205 for(i=0; i<nVector; i++){ 3206 Expr *p; 3207 CollSeq *pColl; 3208 int r3 = sqlite3GetTempReg(pParse); 3209 p = sqlite3VectorFieldSubexpr(pLeft, i); 3210 pColl = sqlite3ExprCollSeq(pParse, p); 3211 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3); 3212 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, 3213 (void*)pColl, P4_COLLSEQ); 3214 VdbeCoverage(v); 3215 sqlite3ReleaseTempReg(pParse, r3); 3216 } 3217 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); 3218 if( nVector>1 ){ 3219 sqlite3VdbeResolveLabel(v, destNotNull); 3220 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1); 3221 VdbeCoverage(v); 3222 3223 /* Step 7: If we reach this point, we know that the result must 3224 ** be false. */ 3225 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); 3226 } 3227 3228 /* Jumps here in order to return true. */ 3229 sqlite3VdbeJumpHere(v, addrTruthOp); 3230 3231 sqlite3ExprCodeIN_finished: 3232 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs); 3233 VdbeComment((v, "end IN expr")); 3234 sqlite3ExprCodeIN_oom_error: 3235 sqlite3DbFree(pParse->db, aiMap); 3236 sqlite3DbFree(pParse->db, zAff); 3237 } 3238 #endif /* SQLITE_OMIT_SUBQUERY */ 3239 3240 #ifndef SQLITE_OMIT_FLOATING_POINT 3241 /* 3242 ** Generate an instruction that will put the floating point 3243 ** value described by z[0..n-1] into register iMem. 3244 ** 3245 ** The z[] string will probably not be zero-terminated. But the 3246 ** z[n] character is guaranteed to be something that does not look 3247 ** like the continuation of the number. 3248 */ 3249 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ 3250 if( ALWAYS(z!=0) ){ 3251 double value; 3252 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); 3253 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ 3254 if( negateFlag ) value = -value; 3255 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); 3256 } 3257 } 3258 #endif 3259 3260 3261 /* 3262 ** Generate an instruction that will put the integer describe by 3263 ** text z[0..n-1] into register iMem. 3264 ** 3265 ** Expr.u.zToken is always UTF8 and zero-terminated. 3266 */ 3267 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ 3268 Vdbe *v = pParse->pVdbe; 3269 if( pExpr->flags & EP_IntValue ){ 3270 int i = pExpr->u.iValue; 3271 assert( i>=0 ); 3272 if( negFlag ) i = -i; 3273 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); 3274 }else{ 3275 int c; 3276 i64 value; 3277 const char *z = pExpr->u.zToken; 3278 assert( z!=0 ); 3279 c = sqlite3DecOrHexToI64(z, &value); 3280 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){ 3281 #ifdef SQLITE_OMIT_FLOATING_POINT 3282 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); 3283 #else 3284 #ifndef SQLITE_OMIT_HEX_INTEGER 3285 if( sqlite3_strnicmp(z,"0x",2)==0 ){ 3286 sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z); 3287 }else 3288 #endif 3289 { 3290 codeReal(v, z, negFlag, iMem); 3291 } 3292 #endif 3293 }else{ 3294 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; } 3295 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); 3296 } 3297 } 3298 } 3299 3300 3301 /* Generate code that will load into register regOut a value that is 3302 ** appropriate for the iIdxCol-th column of index pIdx. 3303 */ 3304 void sqlite3ExprCodeLoadIndexColumn( 3305 Parse *pParse, /* The parsing context */ 3306 Index *pIdx, /* The index whose column is to be loaded */ 3307 int iTabCur, /* Cursor pointing to a table row */ 3308 int iIdxCol, /* The column of the index to be loaded */ 3309 int regOut /* Store the index column value in this register */ 3310 ){ 3311 i16 iTabCol = pIdx->aiColumn[iIdxCol]; 3312 if( iTabCol==XN_EXPR ){ 3313 assert( pIdx->aColExpr ); 3314 assert( pIdx->aColExpr->nExpr>iIdxCol ); 3315 pParse->iSelfTab = iTabCur + 1; 3316 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); 3317 pParse->iSelfTab = 0; 3318 }else{ 3319 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, 3320 iTabCol, regOut); 3321 } 3322 } 3323 3324 /* 3325 ** Generate code to extract the value of the iCol-th column of a table. 3326 */ 3327 void sqlite3ExprCodeGetColumnOfTable( 3328 Vdbe *v, /* The VDBE under construction */ 3329 Table *pTab, /* The table containing the value */ 3330 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ 3331 int iCol, /* Index of the column to extract */ 3332 int regOut /* Extract the value into this register */ 3333 ){ 3334 if( pTab==0 ){ 3335 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut); 3336 return; 3337 } 3338 if( iCol<0 || iCol==pTab->iPKey ){ 3339 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); 3340 }else{ 3341 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; 3342 int x = iCol; 3343 if( !HasRowid(pTab) && !IsVirtual(pTab) ){ 3344 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol); 3345 } 3346 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); 3347 } 3348 if( iCol>=0 ){ 3349 sqlite3ColumnDefault(v, pTab, iCol, regOut); 3350 } 3351 } 3352 3353 /* 3354 ** Generate code that will extract the iColumn-th column from 3355 ** table pTab and store the column value in register iReg. 3356 ** 3357 ** There must be an open cursor to pTab in iTable when this routine 3358 ** is called. If iColumn<0 then code is generated that extracts the rowid. 3359 */ 3360 int sqlite3ExprCodeGetColumn( 3361 Parse *pParse, /* Parsing and code generating context */ 3362 Table *pTab, /* Description of the table we are reading from */ 3363 int iColumn, /* Index of the table column */ 3364 int iTable, /* The cursor pointing to the table */ 3365 int iReg, /* Store results here */ 3366 u8 p5 /* P5 value for OP_Column + FLAGS */ 3367 ){ 3368 Vdbe *v = pParse->pVdbe; 3369 assert( v!=0 ); 3370 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg); 3371 if( p5 ){ 3372 sqlite3VdbeChangeP5(v, p5); 3373 } 3374 return iReg; 3375 } 3376 3377 /* 3378 ** Generate code to move content from registers iFrom...iFrom+nReg-1 3379 ** over to iTo..iTo+nReg-1. 3380 */ 3381 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ 3382 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo ); 3383 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); 3384 } 3385 3386 /* 3387 ** Convert a scalar expression node to a TK_REGISTER referencing 3388 ** register iReg. The caller must ensure that iReg already contains 3389 ** the correct value for the expression. 3390 */ 3391 static void exprToRegister(Expr *pExpr, int iReg){ 3392 Expr *p = sqlite3ExprSkipCollate(pExpr); 3393 p->op2 = p->op; 3394 p->op = TK_REGISTER; 3395 p->iTable = iReg; 3396 ExprClearProperty(p, EP_Skip); 3397 } 3398 3399 /* 3400 ** Evaluate an expression (either a vector or a scalar expression) and store 3401 ** the result in continguous temporary registers. Return the index of 3402 ** the first register used to store the result. 3403 ** 3404 ** If the returned result register is a temporary scalar, then also write 3405 ** that register number into *piFreeable. If the returned result register 3406 ** is not a temporary or if the expression is a vector set *piFreeable 3407 ** to 0. 3408 */ 3409 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ 3410 int iResult; 3411 int nResult = sqlite3ExprVectorSize(p); 3412 if( nResult==1 ){ 3413 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable); 3414 }else{ 3415 *piFreeable = 0; 3416 if( p->op==TK_SELECT ){ 3417 #if SQLITE_OMIT_SUBQUERY 3418 iResult = 0; 3419 #else 3420 iResult = sqlite3CodeSubselect(pParse, p); 3421 #endif 3422 }else{ 3423 int i; 3424 iResult = pParse->nMem+1; 3425 pParse->nMem += nResult; 3426 for(i=0; i<nResult; i++){ 3427 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult); 3428 } 3429 } 3430 } 3431 return iResult; 3432 } 3433 3434 3435 /* 3436 ** Generate code into the current Vdbe to evaluate the given 3437 ** expression. Attempt to store the results in register "target". 3438 ** Return the register where results are stored. 3439 ** 3440 ** With this routine, there is no guarantee that results will 3441 ** be stored in target. The result might be stored in some other 3442 ** register if it is convenient to do so. The calling function 3443 ** must check the return code and move the results to the desired 3444 ** register. 3445 */ 3446 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ 3447 Vdbe *v = pParse->pVdbe; /* The VM under construction */ 3448 int op; /* The opcode being coded */ 3449 int inReg = target; /* Results stored in register inReg */ 3450 int regFree1 = 0; /* If non-zero free this temporary register */ 3451 int regFree2 = 0; /* If non-zero free this temporary register */ 3452 int r1, r2; /* Various register numbers */ 3453 Expr tempX; /* Temporary expression node */ 3454 int p5 = 0; 3455 3456 assert( target>0 && target<=pParse->nMem ); 3457 if( v==0 ){ 3458 assert( pParse->db->mallocFailed ); 3459 return 0; 3460 } 3461 3462 expr_code_doover: 3463 if( pExpr==0 ){ 3464 op = TK_NULL; 3465 }else{ 3466 op = pExpr->op; 3467 } 3468 switch( op ){ 3469 case TK_AGG_COLUMN: { 3470 AggInfo *pAggInfo = pExpr->pAggInfo; 3471 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; 3472 if( !pAggInfo->directMode ){ 3473 assert( pCol->iMem>0 ); 3474 return pCol->iMem; 3475 }else if( pAggInfo->useSortingIdx ){ 3476 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, 3477 pCol->iSorterColumn, target); 3478 return target; 3479 } 3480 /* Otherwise, fall thru into the TK_COLUMN case */ 3481 } 3482 case TK_COLUMN: { 3483 int iTab = pExpr->iTable; 3484 if( ExprHasProperty(pExpr, EP_FixedCol) ){ 3485 /* This COLUMN expression is really a constant due to WHERE clause 3486 ** constraints, and that constant is coded by the pExpr->pLeft 3487 ** expresssion. However, make sure the constant has the correct 3488 ** datatype by applying the Affinity of the table column to the 3489 ** constant. 3490 */ 3491 int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target); 3492 int aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); 3493 if( aff!=SQLITE_AFF_BLOB ){ 3494 static const char zAff[] = "B\000C\000D\000E"; 3495 assert( SQLITE_AFF_BLOB=='A' ); 3496 assert( SQLITE_AFF_TEXT=='B' ); 3497 if( iReg!=target ){ 3498 sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target); 3499 iReg = target; 3500 } 3501 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0, 3502 &zAff[(aff-'B')*2], P4_STATIC); 3503 } 3504 return iReg; 3505 } 3506 if( iTab<0 ){ 3507 if( pParse->iSelfTab<0 ){ 3508 /* Generating CHECK constraints or inserting into partial index */ 3509 return pExpr->iColumn - pParse->iSelfTab; 3510 }else{ 3511 /* Coding an expression that is part of an index where column names 3512 ** in the index refer to the table to which the index belongs */ 3513 iTab = pParse->iSelfTab - 1; 3514 } 3515 } 3516 return sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab, 3517 pExpr->iColumn, iTab, target, 3518 pExpr->op2); 3519 } 3520 case TK_INTEGER: { 3521 codeInteger(pParse, pExpr, 0, target); 3522 return target; 3523 } 3524 case TK_TRUEFALSE: { 3525 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target); 3526 return target; 3527 } 3528 #ifndef SQLITE_OMIT_FLOATING_POINT 3529 case TK_FLOAT: { 3530 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 3531 codeReal(v, pExpr->u.zToken, 0, target); 3532 return target; 3533 } 3534 #endif 3535 case TK_STRING: { 3536 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 3537 sqlite3VdbeLoadString(v, target, pExpr->u.zToken); 3538 return target; 3539 } 3540 case TK_NULL: { 3541 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 3542 return target; 3543 } 3544 #ifndef SQLITE_OMIT_BLOB_LITERAL 3545 case TK_BLOB: { 3546 int n; 3547 const char *z; 3548 char *zBlob; 3549 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 3550 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); 3551 assert( pExpr->u.zToken[1]=='\'' ); 3552 z = &pExpr->u.zToken[2]; 3553 n = sqlite3Strlen30(z) - 1; 3554 assert( z[n]=='\'' ); 3555 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); 3556 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); 3557 return target; 3558 } 3559 #endif 3560 case TK_VARIABLE: { 3561 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 3562 assert( pExpr->u.zToken!=0 ); 3563 assert( pExpr->u.zToken[0]!=0 ); 3564 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); 3565 if( pExpr->u.zToken[1]!=0 ){ 3566 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn); 3567 assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 ); 3568 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */ 3569 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC); 3570 } 3571 return target; 3572 } 3573 case TK_REGISTER: { 3574 return pExpr->iTable; 3575 } 3576 #ifndef SQLITE_OMIT_CAST 3577 case TK_CAST: { 3578 /* Expressions of the form: CAST(pLeft AS token) */ 3579 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); 3580 if( inReg!=target ){ 3581 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); 3582 inReg = target; 3583 } 3584 sqlite3VdbeAddOp2(v, OP_Cast, target, 3585 sqlite3AffinityType(pExpr->u.zToken, 0)); 3586 return inReg; 3587 } 3588 #endif /* SQLITE_OMIT_CAST */ 3589 case TK_IS: 3590 case TK_ISNOT: 3591 op = (op==TK_IS) ? TK_EQ : TK_NE; 3592 p5 = SQLITE_NULLEQ; 3593 /* fall-through */ 3594 case TK_LT: 3595 case TK_LE: 3596 case TK_GT: 3597 case TK_GE: 3598 case TK_NE: 3599 case TK_EQ: { 3600 Expr *pLeft = pExpr->pLeft; 3601 if( sqlite3ExprIsVector(pLeft) ){ 3602 codeVectorCompare(pParse, pExpr, target, op, p5); 3603 }else{ 3604 r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); 3605 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 3606 codeCompare(pParse, pLeft, pExpr->pRight, op, 3607 r1, r2, inReg, SQLITE_STOREP2 | p5); 3608 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 3609 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 3610 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 3611 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 3612 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); 3613 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); 3614 testcase( regFree1==0 ); 3615 testcase( regFree2==0 ); 3616 } 3617 break; 3618 } 3619 case TK_AND: 3620 case TK_OR: 3621 case TK_PLUS: 3622 case TK_STAR: 3623 case TK_MINUS: 3624 case TK_REM: 3625 case TK_BITAND: 3626 case TK_BITOR: 3627 case TK_SLASH: 3628 case TK_LSHIFT: 3629 case TK_RSHIFT: 3630 case TK_CONCAT: { 3631 assert( TK_AND==OP_And ); testcase( op==TK_AND ); 3632 assert( TK_OR==OP_Or ); testcase( op==TK_OR ); 3633 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS ); 3634 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS ); 3635 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM ); 3636 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND ); 3637 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR ); 3638 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH ); 3639 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); 3640 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); 3641 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); 3642 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3643 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 3644 sqlite3VdbeAddOp3(v, op, r2, r1, target); 3645 testcase( regFree1==0 ); 3646 testcase( regFree2==0 ); 3647 break; 3648 } 3649 case TK_UMINUS: { 3650 Expr *pLeft = pExpr->pLeft; 3651 assert( pLeft ); 3652 if( pLeft->op==TK_INTEGER ){ 3653 codeInteger(pParse, pLeft, 1, target); 3654 return target; 3655 #ifndef SQLITE_OMIT_FLOATING_POINT 3656 }else if( pLeft->op==TK_FLOAT ){ 3657 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 3658 codeReal(v, pLeft->u.zToken, 1, target); 3659 return target; 3660 #endif 3661 }else{ 3662 tempX.op = TK_INTEGER; 3663 tempX.flags = EP_IntValue|EP_TokenOnly; 3664 tempX.u.iValue = 0; 3665 r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1); 3666 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); 3667 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); 3668 testcase( regFree2==0 ); 3669 } 3670 break; 3671 } 3672 case TK_BITNOT: 3673 case TK_NOT: { 3674 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT ); 3675 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT ); 3676 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3677 testcase( regFree1==0 ); 3678 sqlite3VdbeAddOp2(v, op, r1, inReg); 3679 break; 3680 } 3681 case TK_TRUTH: { 3682 int isTrue; /* IS TRUE or IS NOT TRUE */ 3683 int bNormal; /* IS TRUE or IS FALSE */ 3684 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3685 testcase( regFree1==0 ); 3686 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 3687 bNormal = pExpr->op2==TK_IS; 3688 testcase( isTrue && bNormal); 3689 testcase( !isTrue && bNormal); 3690 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal); 3691 break; 3692 } 3693 case TK_ISNULL: 3694 case TK_NOTNULL: { 3695 int addr; 3696 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); 3697 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); 3698 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 3699 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3700 testcase( regFree1==0 ); 3701 addr = sqlite3VdbeAddOp1(v, op, r1); 3702 VdbeCoverageIf(v, op==TK_ISNULL); 3703 VdbeCoverageIf(v, op==TK_NOTNULL); 3704 sqlite3VdbeAddOp2(v, OP_Integer, 0, target); 3705 sqlite3VdbeJumpHere(v, addr); 3706 break; 3707 } 3708 case TK_AGG_FUNCTION: { 3709 AggInfo *pInfo = pExpr->pAggInfo; 3710 if( pInfo==0 ){ 3711 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 3712 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); 3713 }else{ 3714 return pInfo->aFunc[pExpr->iAgg].iMem; 3715 } 3716 break; 3717 } 3718 case TK_FUNCTION: { 3719 ExprList *pFarg; /* List of function arguments */ 3720 int nFarg; /* Number of function arguments */ 3721 FuncDef *pDef; /* The function definition object */ 3722 const char *zId; /* The function name */ 3723 u32 constMask = 0; /* Mask of function arguments that are constant */ 3724 int i; /* Loop counter */ 3725 sqlite3 *db = pParse->db; /* The database connection */ 3726 u8 enc = ENC(db); /* The text encoding used by this database */ 3727 CollSeq *pColl = 0; /* A collating sequence */ 3728 3729 #ifndef SQLITE_OMIT_WINDOWFUNC 3730 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 3731 return pExpr->y.pWin->regResult; 3732 } 3733 #endif 3734 3735 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){ 3736 /* SQL functions can be expensive. So try to move constant functions 3737 ** out of the inner loop, even if that means an extra OP_Copy. */ 3738 return sqlite3ExprCodeAtInit(pParse, pExpr, -1); 3739 } 3740 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 3741 if( ExprHasProperty(pExpr, EP_TokenOnly) ){ 3742 pFarg = 0; 3743 }else{ 3744 pFarg = pExpr->x.pList; 3745 } 3746 nFarg = pFarg ? pFarg->nExpr : 0; 3747 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 3748 zId = pExpr->u.zToken; 3749 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0); 3750 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 3751 if( pDef==0 && pParse->explain ){ 3752 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); 3753 } 3754 #endif 3755 if( pDef==0 || pDef->xFinalize!=0 ){ 3756 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId); 3757 break; 3758 } 3759 3760 /* Attempt a direct implementation of the built-in COALESCE() and 3761 ** IFNULL() functions. This avoids unnecessary evaluation of 3762 ** arguments past the first non-NULL argument. 3763 */ 3764 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){ 3765 int endCoalesce = sqlite3VdbeMakeLabel(pParse); 3766 assert( nFarg>=2 ); 3767 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); 3768 for(i=1; i<nFarg; i++){ 3769 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce); 3770 VdbeCoverage(v); 3771 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target); 3772 } 3773 sqlite3VdbeResolveLabel(v, endCoalesce); 3774 break; 3775 } 3776 3777 /* The UNLIKELY() function is a no-op. The result is the value 3778 ** of the first argument. 3779 */ 3780 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ 3781 assert( nFarg>=1 ); 3782 return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); 3783 } 3784 3785 #ifdef SQLITE_DEBUG 3786 /* The AFFINITY() function evaluates to a string that describes 3787 ** the type affinity of the argument. This is used for testing of 3788 ** the SQLite type logic. 3789 */ 3790 if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){ 3791 const char *azAff[] = { "blob", "text", "numeric", "integer", "real" }; 3792 char aff; 3793 assert( nFarg==1 ); 3794 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr); 3795 sqlite3VdbeLoadString(v, target, 3796 aff ? azAff[aff-SQLITE_AFF_BLOB] : "none"); 3797 return target; 3798 } 3799 #endif 3800 3801 for(i=0; i<nFarg; i++){ 3802 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){ 3803 testcase( i==31 ); 3804 constMask |= MASKBIT32(i); 3805 } 3806 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ 3807 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); 3808 } 3809 } 3810 if( pFarg ){ 3811 if( constMask ){ 3812 r1 = pParse->nMem+1; 3813 pParse->nMem += nFarg; 3814 }else{ 3815 r1 = sqlite3GetTempRange(pParse, nFarg); 3816 } 3817 3818 /* For length() and typeof() functions with a column argument, 3819 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG 3820 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data 3821 ** loading. 3822 */ 3823 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ 3824 u8 exprOp; 3825 assert( nFarg==1 ); 3826 assert( pFarg->a[0].pExpr!=0 ); 3827 exprOp = pFarg->a[0].pExpr->op; 3828 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ 3829 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); 3830 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); 3831 testcase( pDef->funcFlags & OPFLAG_LENGTHARG ); 3832 pFarg->a[0].pExpr->op2 = 3833 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG); 3834 } 3835 } 3836 3837 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, 3838 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR); 3839 }else{ 3840 r1 = 0; 3841 } 3842 #ifndef SQLITE_OMIT_VIRTUALTABLE 3843 /* Possibly overload the function if the first argument is 3844 ** a virtual table column. 3845 ** 3846 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the 3847 ** second argument, not the first, as the argument to test to 3848 ** see if it is a column in a virtual table. This is done because 3849 ** the left operand of infix functions (the operand we want to 3850 ** control overloading) ends up as the second argument to the 3851 ** function. The expression "A glob B" is equivalent to 3852 ** "glob(B,A). We want to use the A in "A glob B" to test 3853 ** for function overloading. But we use the B term in "glob(B,A)". 3854 */ 3855 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){ 3856 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); 3857 }else if( nFarg>0 ){ 3858 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); 3859 } 3860 #endif 3861 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 3862 if( !pColl ) pColl = db->pDfltColl; 3863 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 3864 } 3865 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 3866 if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){ 3867 Expr *pArg = pFarg->a[0].pExpr; 3868 if( pArg->op==TK_COLUMN ){ 3869 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target); 3870 }else{ 3871 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 3872 } 3873 }else 3874 #endif 3875 { 3876 sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0, 3877 constMask, r1, target, (char*)pDef, P4_FUNCDEF); 3878 sqlite3VdbeChangeP5(v, (u8)nFarg); 3879 } 3880 if( nFarg && constMask==0 ){ 3881 sqlite3ReleaseTempRange(pParse, r1, nFarg); 3882 } 3883 return target; 3884 } 3885 #ifndef SQLITE_OMIT_SUBQUERY 3886 case TK_EXISTS: 3887 case TK_SELECT: { 3888 int nCol; 3889 testcase( op==TK_EXISTS ); 3890 testcase( op==TK_SELECT ); 3891 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){ 3892 sqlite3SubselectError(pParse, nCol, 1); 3893 }else{ 3894 return sqlite3CodeSubselect(pParse, pExpr); 3895 } 3896 break; 3897 } 3898 case TK_SELECT_COLUMN: { 3899 int n; 3900 if( pExpr->pLeft->iTable==0 ){ 3901 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft); 3902 } 3903 assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT ); 3904 if( pExpr->iTable 3905 && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft)) 3906 ){ 3907 sqlite3ErrorMsg(pParse, "%d columns assigned %d values", 3908 pExpr->iTable, n); 3909 } 3910 return pExpr->pLeft->iTable + pExpr->iColumn; 3911 } 3912 case TK_IN: { 3913 int destIfFalse = sqlite3VdbeMakeLabel(pParse); 3914 int destIfNull = sqlite3VdbeMakeLabel(pParse); 3915 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 3916 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 3917 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 3918 sqlite3VdbeResolveLabel(v, destIfFalse); 3919 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); 3920 sqlite3VdbeResolveLabel(v, destIfNull); 3921 return target; 3922 } 3923 #endif /* SQLITE_OMIT_SUBQUERY */ 3924 3925 3926 /* 3927 ** x BETWEEN y AND z 3928 ** 3929 ** This is equivalent to 3930 ** 3931 ** x>=y AND x<=z 3932 ** 3933 ** X is stored in pExpr->pLeft. 3934 ** Y is stored in pExpr->pList->a[0].pExpr. 3935 ** Z is stored in pExpr->pList->a[1].pExpr. 3936 */ 3937 case TK_BETWEEN: { 3938 exprCodeBetween(pParse, pExpr, target, 0, 0); 3939 return target; 3940 } 3941 case TK_SPAN: 3942 case TK_COLLATE: 3943 case TK_UPLUS: { 3944 pExpr = pExpr->pLeft; 3945 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */ 3946 } 3947 3948 case TK_TRIGGER: { 3949 /* If the opcode is TK_TRIGGER, then the expression is a reference 3950 ** to a column in the new.* or old.* pseudo-tables available to 3951 ** trigger programs. In this case Expr.iTable is set to 1 for the 3952 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn 3953 ** is set to the column of the pseudo-table to read, or to -1 to 3954 ** read the rowid field. 3955 ** 3956 ** The expression is implemented using an OP_Param opcode. The p1 3957 ** parameter is set to 0 for an old.rowid reference, or to (i+1) 3958 ** to reference another column of the old.* pseudo-table, where 3959 ** i is the index of the column. For a new.rowid reference, p1 is 3960 ** set to (n+1), where n is the number of columns in each pseudo-table. 3961 ** For a reference to any other column in the new.* pseudo-table, p1 3962 ** is set to (n+2+i), where n and i are as defined previously. For 3963 ** example, if the table on which triggers are being fired is 3964 ** declared as: 3965 ** 3966 ** CREATE TABLE t1(a, b); 3967 ** 3968 ** Then p1 is interpreted as follows: 3969 ** 3970 ** p1==0 -> old.rowid p1==3 -> new.rowid 3971 ** p1==1 -> old.a p1==4 -> new.a 3972 ** p1==2 -> old.b p1==5 -> new.b 3973 */ 3974 Table *pTab = pExpr->y.pTab; 3975 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn; 3976 3977 assert( pExpr->iTable==0 || pExpr->iTable==1 ); 3978 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol ); 3979 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey ); 3980 assert( p1>=0 && p1<(pTab->nCol*2+2) ); 3981 3982 sqlite3VdbeAddOp2(v, OP_Param, p1, target); 3983 VdbeComment((v, "r[%d]=%s.%s", target, 3984 (pExpr->iTable ? "new" : "old"), 3985 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[pExpr->iColumn].zName) 3986 )); 3987 3988 #ifndef SQLITE_OMIT_FLOATING_POINT 3989 /* If the column has REAL affinity, it may currently be stored as an 3990 ** integer. Use OP_RealAffinity to make sure it is really real. 3991 ** 3992 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to 3993 ** floating point when extracting it from the record. */ 3994 if( pExpr->iColumn>=0 3995 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL 3996 ){ 3997 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 3998 } 3999 #endif 4000 break; 4001 } 4002 4003 case TK_VECTOR: { 4004 sqlite3ErrorMsg(pParse, "row value misused"); 4005 break; 4006 } 4007 4008 case TK_IF_NULL_ROW: { 4009 int addrINR; 4010 addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable); 4011 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); 4012 sqlite3VdbeJumpHere(v, addrINR); 4013 sqlite3VdbeChangeP3(v, addrINR, inReg); 4014 break; 4015 } 4016 4017 /* 4018 ** Form A: 4019 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 4020 ** 4021 ** Form B: 4022 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 4023 ** 4024 ** Form A is can be transformed into the equivalent form B as follows: 4025 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... 4026 ** WHEN x=eN THEN rN ELSE y END 4027 ** 4028 ** X (if it exists) is in pExpr->pLeft. 4029 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is 4030 ** odd. The Y is also optional. If the number of elements in x.pList 4031 ** is even, then Y is omitted and the "otherwise" result is NULL. 4032 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. 4033 ** 4034 ** The result of the expression is the Ri for the first matching Ei, 4035 ** or if there is no matching Ei, the ELSE term Y, or if there is 4036 ** no ELSE term, NULL. 4037 */ 4038 default: assert( op==TK_CASE ); { 4039 int endLabel; /* GOTO label for end of CASE stmt */ 4040 int nextCase; /* GOTO label for next WHEN clause */ 4041 int nExpr; /* 2x number of WHEN terms */ 4042 int i; /* Loop counter */ 4043 ExprList *pEList; /* List of WHEN terms */ 4044 struct ExprList_item *aListelem; /* Array of WHEN terms */ 4045 Expr opCompare; /* The X==Ei expression */ 4046 Expr *pX; /* The X expression */ 4047 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ 4048 Expr *pDel = 0; 4049 sqlite3 *db = pParse->db; 4050 4051 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); 4052 assert(pExpr->x.pList->nExpr > 0); 4053 pEList = pExpr->x.pList; 4054 aListelem = pEList->a; 4055 nExpr = pEList->nExpr; 4056 endLabel = sqlite3VdbeMakeLabel(pParse); 4057 if( (pX = pExpr->pLeft)!=0 ){ 4058 pDel = sqlite3ExprDup(db, pX, 0); 4059 if( db->mallocFailed ){ 4060 sqlite3ExprDelete(db, pDel); 4061 break; 4062 } 4063 testcase( pX->op==TK_COLUMN ); 4064 exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); 4065 testcase( regFree1==0 ); 4066 memset(&opCompare, 0, sizeof(opCompare)); 4067 opCompare.op = TK_EQ; 4068 opCompare.pLeft = pDel; 4069 pTest = &opCompare; 4070 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: 4071 ** The value in regFree1 might get SCopy-ed into the file result. 4072 ** So make sure that the regFree1 register is not reused for other 4073 ** purposes and possibly overwritten. */ 4074 regFree1 = 0; 4075 } 4076 for(i=0; i<nExpr-1; i=i+2){ 4077 if( pX ){ 4078 assert( pTest!=0 ); 4079 opCompare.pRight = aListelem[i].pExpr; 4080 }else{ 4081 pTest = aListelem[i].pExpr; 4082 } 4083 nextCase = sqlite3VdbeMakeLabel(pParse); 4084 testcase( pTest->op==TK_COLUMN ); 4085 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); 4086 testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); 4087 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); 4088 sqlite3VdbeGoto(v, endLabel); 4089 sqlite3VdbeResolveLabel(v, nextCase); 4090 } 4091 if( (nExpr&1)!=0 ){ 4092 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); 4093 }else{ 4094 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 4095 } 4096 sqlite3ExprDelete(db, pDel); 4097 sqlite3VdbeResolveLabel(v, endLabel); 4098 break; 4099 } 4100 #ifndef SQLITE_OMIT_TRIGGER 4101 case TK_RAISE: { 4102 assert( pExpr->affinity==OE_Rollback 4103 || pExpr->affinity==OE_Abort 4104 || pExpr->affinity==OE_Fail 4105 || pExpr->affinity==OE_Ignore 4106 ); 4107 if( !pParse->pTriggerTab ){ 4108 sqlite3ErrorMsg(pParse, 4109 "RAISE() may only be used within a trigger-program"); 4110 return 0; 4111 } 4112 if( pExpr->affinity==OE_Abort ){ 4113 sqlite3MayAbort(pParse); 4114 } 4115 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4116 if( pExpr->affinity==OE_Ignore ){ 4117 sqlite3VdbeAddOp4( 4118 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); 4119 VdbeCoverage(v); 4120 }else{ 4121 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER, 4122 pExpr->affinity, pExpr->u.zToken, 0, 0); 4123 } 4124 4125 break; 4126 } 4127 #endif 4128 } 4129 sqlite3ReleaseTempReg(pParse, regFree1); 4130 sqlite3ReleaseTempReg(pParse, regFree2); 4131 return inReg; 4132 } 4133 4134 /* 4135 ** Factor out the code of the given expression to initialization time. 4136 ** 4137 ** If regDest>=0 then the result is always stored in that register and the 4138 ** result is not reusable. If regDest<0 then this routine is free to 4139 ** store the value whereever it wants. The register where the expression 4140 ** is stored is returned. When regDest<0, two identical expressions will 4141 ** code to the same register. 4142 */ 4143 int sqlite3ExprCodeAtInit( 4144 Parse *pParse, /* Parsing context */ 4145 Expr *pExpr, /* The expression to code when the VDBE initializes */ 4146 int regDest /* Store the value in this register */ 4147 ){ 4148 ExprList *p; 4149 assert( ConstFactorOk(pParse) ); 4150 p = pParse->pConstExpr; 4151 if( regDest<0 && p ){ 4152 struct ExprList_item *pItem; 4153 int i; 4154 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ 4155 if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){ 4156 return pItem->u.iConstExprReg; 4157 } 4158 } 4159 } 4160 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); 4161 p = sqlite3ExprListAppend(pParse, p, pExpr); 4162 if( p ){ 4163 struct ExprList_item *pItem = &p->a[p->nExpr-1]; 4164 pItem->reusable = regDest<0; 4165 if( regDest<0 ) regDest = ++pParse->nMem; 4166 pItem->u.iConstExprReg = regDest; 4167 } 4168 pParse->pConstExpr = p; 4169 return regDest; 4170 } 4171 4172 /* 4173 ** Generate code to evaluate an expression and store the results 4174 ** into a register. Return the register number where the results 4175 ** are stored. 4176 ** 4177 ** If the register is a temporary register that can be deallocated, 4178 ** then write its number into *pReg. If the result register is not 4179 ** a temporary, then set *pReg to zero. 4180 ** 4181 ** If pExpr is a constant, then this routine might generate this 4182 ** code to fill the register in the initialization section of the 4183 ** VDBE program, in order to factor it out of the evaluation loop. 4184 */ 4185 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ 4186 int r2; 4187 pExpr = sqlite3ExprSkipCollate(pExpr); 4188 if( ConstFactorOk(pParse) 4189 && pExpr->op!=TK_REGISTER 4190 && sqlite3ExprIsConstantNotJoin(pExpr) 4191 ){ 4192 *pReg = 0; 4193 r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1); 4194 }else{ 4195 int r1 = sqlite3GetTempReg(pParse); 4196 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); 4197 if( r2==r1 ){ 4198 *pReg = r1; 4199 }else{ 4200 sqlite3ReleaseTempReg(pParse, r1); 4201 *pReg = 0; 4202 } 4203 } 4204 return r2; 4205 } 4206 4207 /* 4208 ** Generate code that will evaluate expression pExpr and store the 4209 ** results in register target. The results are guaranteed to appear 4210 ** in register target. 4211 */ 4212 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ 4213 int inReg; 4214 4215 assert( target>0 && target<=pParse->nMem ); 4216 if( pExpr && pExpr->op==TK_REGISTER ){ 4217 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target); 4218 }else{ 4219 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); 4220 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); 4221 if( inReg!=target && pParse->pVdbe ){ 4222 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target); 4223 } 4224 } 4225 } 4226 4227 /* 4228 ** Make a transient copy of expression pExpr and then code it using 4229 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode() 4230 ** except that the input expression is guaranteed to be unchanged. 4231 */ 4232 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ 4233 sqlite3 *db = pParse->db; 4234 pExpr = sqlite3ExprDup(db, pExpr, 0); 4235 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target); 4236 sqlite3ExprDelete(db, pExpr); 4237 } 4238 4239 /* 4240 ** Generate code that will evaluate expression pExpr and store the 4241 ** results in register target. The results are guaranteed to appear 4242 ** in register target. If the expression is constant, then this routine 4243 ** might choose to code the expression at initialization time. 4244 */ 4245 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ 4246 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){ 4247 sqlite3ExprCodeAtInit(pParse, pExpr, target); 4248 }else{ 4249 sqlite3ExprCode(pParse, pExpr, target); 4250 } 4251 } 4252 4253 /* 4254 ** Generate code that evaluates the given expression and puts the result 4255 ** in register target. 4256 ** 4257 ** Also make a copy of the expression results into another "cache" register 4258 ** and modify the expression so that the next time it is evaluated, 4259 ** the result is a copy of the cache register. 4260 ** 4261 ** This routine is used for expressions that are used multiple 4262 ** times. They are evaluated once and the results of the expression 4263 ** are reused. 4264 */ 4265 void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ 4266 Vdbe *v = pParse->pVdbe; 4267 int iMem; 4268 4269 assert( target>0 ); 4270 assert( pExpr->op!=TK_REGISTER ); 4271 sqlite3ExprCode(pParse, pExpr, target); 4272 iMem = ++pParse->nMem; 4273 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem); 4274 exprToRegister(pExpr, iMem); 4275 } 4276 4277 /* 4278 ** Generate code that pushes the value of every element of the given 4279 ** expression list into a sequence of registers beginning at target. 4280 ** 4281 ** Return the number of elements evaluated. The number returned will 4282 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF 4283 ** is defined. 4284 ** 4285 ** The SQLITE_ECEL_DUP flag prevents the arguments from being 4286 ** filled using OP_SCopy. OP_Copy must be used instead. 4287 ** 4288 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be 4289 ** factored out into initialization code. 4290 ** 4291 ** The SQLITE_ECEL_REF flag means that expressions in the list with 4292 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored 4293 ** in registers at srcReg, and so the value can be copied from there. 4294 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0 4295 ** are simply omitted rather than being copied from srcReg. 4296 */ 4297 int sqlite3ExprCodeExprList( 4298 Parse *pParse, /* Parsing context */ 4299 ExprList *pList, /* The expression list to be coded */ 4300 int target, /* Where to write results */ 4301 int srcReg, /* Source registers if SQLITE_ECEL_REF */ 4302 u8 flags /* SQLITE_ECEL_* flags */ 4303 ){ 4304 struct ExprList_item *pItem; 4305 int i, j, n; 4306 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy; 4307 Vdbe *v = pParse->pVdbe; 4308 assert( pList!=0 ); 4309 assert( target>0 ); 4310 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ 4311 n = pList->nExpr; 4312 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR; 4313 for(pItem=pList->a, i=0; i<n; i++, pItem++){ 4314 Expr *pExpr = pItem->pExpr; 4315 #ifdef SQLITE_ENABLE_SORTER_REFERENCES 4316 if( pItem->bSorterRef ){ 4317 i--; 4318 n--; 4319 }else 4320 #endif 4321 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){ 4322 if( flags & SQLITE_ECEL_OMITREF ){ 4323 i--; 4324 n--; 4325 }else{ 4326 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); 4327 } 4328 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 4329 && sqlite3ExprIsConstantNotJoin(pExpr) 4330 ){ 4331 sqlite3ExprCodeAtInit(pParse, pExpr, target+i); 4332 }else{ 4333 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); 4334 if( inReg!=target+i ){ 4335 VdbeOp *pOp; 4336 if( copyOp==OP_Copy 4337 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy 4338 && pOp->p1+pOp->p3+1==inReg 4339 && pOp->p2+pOp->p3+1==target+i 4340 ){ 4341 pOp->p3++; 4342 }else{ 4343 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i); 4344 } 4345 } 4346 } 4347 } 4348 return n; 4349 } 4350 4351 /* 4352 ** Generate code for a BETWEEN operator. 4353 ** 4354 ** x BETWEEN y AND z 4355 ** 4356 ** The above is equivalent to 4357 ** 4358 ** x>=y AND x<=z 4359 ** 4360 ** Code it as such, taking care to do the common subexpression 4361 ** elimination of x. 4362 ** 4363 ** The xJumpIf parameter determines details: 4364 ** 4365 ** NULL: Store the boolean result in reg[dest] 4366 ** sqlite3ExprIfTrue: Jump to dest if true 4367 ** sqlite3ExprIfFalse: Jump to dest if false 4368 ** 4369 ** The jumpIfNull parameter is ignored if xJumpIf is NULL. 4370 */ 4371 static void exprCodeBetween( 4372 Parse *pParse, /* Parsing and code generating context */ 4373 Expr *pExpr, /* The BETWEEN expression */ 4374 int dest, /* Jump destination or storage location */ 4375 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */ 4376 int jumpIfNull /* Take the jump if the BETWEEN is NULL */ 4377 ){ 4378 Expr exprAnd; /* The AND operator in x>=y AND x<=z */ 4379 Expr compLeft; /* The x>=y term */ 4380 Expr compRight; /* The x<=z term */ 4381 int regFree1 = 0; /* Temporary use register */ 4382 Expr *pDel = 0; 4383 sqlite3 *db = pParse->db; 4384 4385 memset(&compLeft, 0, sizeof(Expr)); 4386 memset(&compRight, 0, sizeof(Expr)); 4387 memset(&exprAnd, 0, sizeof(Expr)); 4388 4389 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 4390 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0); 4391 if( db->mallocFailed==0 ){ 4392 exprAnd.op = TK_AND; 4393 exprAnd.pLeft = &compLeft; 4394 exprAnd.pRight = &compRight; 4395 compLeft.op = TK_GE; 4396 compLeft.pLeft = pDel; 4397 compLeft.pRight = pExpr->x.pList->a[0].pExpr; 4398 compRight.op = TK_LE; 4399 compRight.pLeft = pDel; 4400 compRight.pRight = pExpr->x.pList->a[1].pExpr; 4401 exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); 4402 if( xJump ){ 4403 xJump(pParse, &exprAnd, dest, jumpIfNull); 4404 }else{ 4405 /* Mark the expression is being from the ON or USING clause of a join 4406 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move 4407 ** it into the Parse.pConstExpr list. We should use a new bit for this, 4408 ** for clarity, but we are out of bits in the Expr.flags field so we 4409 ** have to reuse the EP_FromJoin bit. Bummer. */ 4410 pDel->flags |= EP_FromJoin; 4411 sqlite3ExprCodeTarget(pParse, &exprAnd, dest); 4412 } 4413 sqlite3ReleaseTempReg(pParse, regFree1); 4414 } 4415 sqlite3ExprDelete(db, pDel); 4416 4417 /* Ensure adequate test coverage */ 4418 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); 4419 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); 4420 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); 4421 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); 4422 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); 4423 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); 4424 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); 4425 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); 4426 testcase( xJump==0 ); 4427 } 4428 4429 /* 4430 ** Generate code for a boolean expression such that a jump is made 4431 ** to the label "dest" if the expression is true but execution 4432 ** continues straight thru if the expression is false. 4433 ** 4434 ** If the expression evaluates to NULL (neither true nor false), then 4435 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. 4436 ** 4437 ** This code depends on the fact that certain token values (ex: TK_EQ) 4438 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding 4439 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in 4440 ** the make process cause these values to align. Assert()s in the code 4441 ** below verify that the numbers are aligned correctly. 4442 */ 4443 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 4444 Vdbe *v = pParse->pVdbe; 4445 int op = 0; 4446 int regFree1 = 0; 4447 int regFree2 = 0; 4448 int r1, r2; 4449 4450 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 4451 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ 4452 if( NEVER(pExpr==0) ) return; /* No way this can happen */ 4453 op = pExpr->op; 4454 switch( op ){ 4455 case TK_AND: 4456 case TK_OR: { 4457 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 4458 if( pAlt!=pExpr ){ 4459 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull); 4460 }else if( op==TK_AND ){ 4461 int d2 = sqlite3VdbeMakeLabel(pParse); 4462 testcase( jumpIfNull==0 ); 4463 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, 4464 jumpIfNull^SQLITE_JUMPIFNULL); 4465 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 4466 sqlite3VdbeResolveLabel(v, d2); 4467 }else{ 4468 testcase( jumpIfNull==0 ); 4469 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 4470 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 4471 } 4472 break; 4473 } 4474 case TK_NOT: { 4475 testcase( jumpIfNull==0 ); 4476 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 4477 break; 4478 } 4479 case TK_TRUTH: { 4480 int isNot; /* IS NOT TRUE or IS NOT FALSE */ 4481 int isTrue; /* IS TRUE or IS NOT TRUE */ 4482 testcase( jumpIfNull==0 ); 4483 isNot = pExpr->op2==TK_ISNOT; 4484 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 4485 testcase( isTrue && isNot ); 4486 testcase( !isTrue && isNot ); 4487 if( isTrue ^ isNot ){ 4488 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 4489 isNot ? SQLITE_JUMPIFNULL : 0); 4490 }else{ 4491 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, 4492 isNot ? SQLITE_JUMPIFNULL : 0); 4493 } 4494 break; 4495 } 4496 case TK_IS: 4497 case TK_ISNOT: 4498 testcase( op==TK_IS ); 4499 testcase( op==TK_ISNOT ); 4500 op = (op==TK_IS) ? TK_EQ : TK_NE; 4501 jumpIfNull = SQLITE_NULLEQ; 4502 /* Fall thru */ 4503 case TK_LT: 4504 case TK_LE: 4505 case TK_GT: 4506 case TK_GE: 4507 case TK_NE: 4508 case TK_EQ: { 4509 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; 4510 testcase( jumpIfNull==0 ); 4511 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 4512 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 4513 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 4514 r1, r2, dest, jumpIfNull); 4515 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 4516 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 4517 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 4518 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 4519 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); 4520 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); 4521 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); 4522 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); 4523 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); 4524 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); 4525 testcase( regFree1==0 ); 4526 testcase( regFree2==0 ); 4527 break; 4528 } 4529 case TK_ISNULL: 4530 case TK_NOTNULL: { 4531 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); 4532 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); 4533 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 4534 sqlite3VdbeAddOp2(v, op, r1, dest); 4535 VdbeCoverageIf(v, op==TK_ISNULL); 4536 VdbeCoverageIf(v, op==TK_NOTNULL); 4537 testcase( regFree1==0 ); 4538 break; 4539 } 4540 case TK_BETWEEN: { 4541 testcase( jumpIfNull==0 ); 4542 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull); 4543 break; 4544 } 4545 #ifndef SQLITE_OMIT_SUBQUERY 4546 case TK_IN: { 4547 int destIfFalse = sqlite3VdbeMakeLabel(pParse); 4548 int destIfNull = jumpIfNull ? dest : destIfFalse; 4549 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 4550 sqlite3VdbeGoto(v, dest); 4551 sqlite3VdbeResolveLabel(v, destIfFalse); 4552 break; 4553 } 4554 #endif 4555 default: { 4556 default_expr: 4557 if( ExprAlwaysTrue(pExpr) ){ 4558 sqlite3VdbeGoto(v, dest); 4559 }else if( ExprAlwaysFalse(pExpr) ){ 4560 /* No-op */ 4561 }else{ 4562 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 4563 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); 4564 VdbeCoverage(v); 4565 testcase( regFree1==0 ); 4566 testcase( jumpIfNull==0 ); 4567 } 4568 break; 4569 } 4570 } 4571 sqlite3ReleaseTempReg(pParse, regFree1); 4572 sqlite3ReleaseTempReg(pParse, regFree2); 4573 } 4574 4575 /* 4576 ** Generate code for a boolean expression such that a jump is made 4577 ** to the label "dest" if the expression is false but execution 4578 ** continues straight thru if the expression is true. 4579 ** 4580 ** If the expression evaluates to NULL (neither true nor false) then 4581 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull 4582 ** is 0. 4583 */ 4584 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 4585 Vdbe *v = pParse->pVdbe; 4586 int op = 0; 4587 int regFree1 = 0; 4588 int regFree2 = 0; 4589 int r1, r2; 4590 4591 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 4592 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ 4593 if( pExpr==0 ) return; 4594 4595 /* The value of pExpr->op and op are related as follows: 4596 ** 4597 ** pExpr->op op 4598 ** --------- ---------- 4599 ** TK_ISNULL OP_NotNull 4600 ** TK_NOTNULL OP_IsNull 4601 ** TK_NE OP_Eq 4602 ** TK_EQ OP_Ne 4603 ** TK_GT OP_Le 4604 ** TK_LE OP_Gt 4605 ** TK_GE OP_Lt 4606 ** TK_LT OP_Ge 4607 ** 4608 ** For other values of pExpr->op, op is undefined and unused. 4609 ** The value of TK_ and OP_ constants are arranged such that we 4610 ** can compute the mapping above using the following expression. 4611 ** Assert()s verify that the computation is correct. 4612 */ 4613 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); 4614 4615 /* Verify correct alignment of TK_ and OP_ constants 4616 */ 4617 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); 4618 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); 4619 assert( pExpr->op!=TK_NE || op==OP_Eq ); 4620 assert( pExpr->op!=TK_EQ || op==OP_Ne ); 4621 assert( pExpr->op!=TK_LT || op==OP_Ge ); 4622 assert( pExpr->op!=TK_LE || op==OP_Gt ); 4623 assert( pExpr->op!=TK_GT || op==OP_Le ); 4624 assert( pExpr->op!=TK_GE || op==OP_Lt ); 4625 4626 switch( pExpr->op ){ 4627 case TK_AND: 4628 case TK_OR: { 4629 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 4630 if( pAlt!=pExpr ){ 4631 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull); 4632 }else if( pExpr->op==TK_AND ){ 4633 testcase( jumpIfNull==0 ); 4634 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 4635 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 4636 }else{ 4637 int d2 = sqlite3VdbeMakeLabel(pParse); 4638 testcase( jumpIfNull==0 ); 4639 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, 4640 jumpIfNull^SQLITE_JUMPIFNULL); 4641 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 4642 sqlite3VdbeResolveLabel(v, d2); 4643 } 4644 break; 4645 } 4646 case TK_NOT: { 4647 testcase( jumpIfNull==0 ); 4648 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 4649 break; 4650 } 4651 case TK_TRUTH: { 4652 int isNot; /* IS NOT TRUE or IS NOT FALSE */ 4653 int isTrue; /* IS TRUE or IS NOT TRUE */ 4654 testcase( jumpIfNull==0 ); 4655 isNot = pExpr->op2==TK_ISNOT; 4656 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 4657 testcase( isTrue && isNot ); 4658 testcase( !isTrue && isNot ); 4659 if( isTrue ^ isNot ){ 4660 /* IS TRUE and IS NOT FALSE */ 4661 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, 4662 isNot ? 0 : SQLITE_JUMPIFNULL); 4663 4664 }else{ 4665 /* IS FALSE and IS NOT TRUE */ 4666 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 4667 isNot ? 0 : SQLITE_JUMPIFNULL); 4668 } 4669 break; 4670 } 4671 case TK_IS: 4672 case TK_ISNOT: 4673 testcase( pExpr->op==TK_IS ); 4674 testcase( pExpr->op==TK_ISNOT ); 4675 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; 4676 jumpIfNull = SQLITE_NULLEQ; 4677 /* Fall thru */ 4678 case TK_LT: 4679 case TK_LE: 4680 case TK_GT: 4681 case TK_GE: 4682 case TK_NE: 4683 case TK_EQ: { 4684 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; 4685 testcase( jumpIfNull==0 ); 4686 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 4687 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 4688 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 4689 r1, r2, dest, jumpIfNull); 4690 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 4691 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 4692 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 4693 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 4694 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); 4695 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); 4696 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); 4697 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); 4698 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); 4699 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); 4700 testcase( regFree1==0 ); 4701 testcase( regFree2==0 ); 4702 break; 4703 } 4704 case TK_ISNULL: 4705 case TK_NOTNULL: { 4706 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 4707 sqlite3VdbeAddOp2(v, op, r1, dest); 4708 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); 4709 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); 4710 testcase( regFree1==0 ); 4711 break; 4712 } 4713 case TK_BETWEEN: { 4714 testcase( jumpIfNull==0 ); 4715 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull); 4716 break; 4717 } 4718 #ifndef SQLITE_OMIT_SUBQUERY 4719 case TK_IN: { 4720 if( jumpIfNull ){ 4721 sqlite3ExprCodeIN(pParse, pExpr, dest, dest); 4722 }else{ 4723 int destIfNull = sqlite3VdbeMakeLabel(pParse); 4724 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); 4725 sqlite3VdbeResolveLabel(v, destIfNull); 4726 } 4727 break; 4728 } 4729 #endif 4730 default: { 4731 default_expr: 4732 if( ExprAlwaysFalse(pExpr) ){ 4733 sqlite3VdbeGoto(v, dest); 4734 }else if( ExprAlwaysTrue(pExpr) ){ 4735 /* no-op */ 4736 }else{ 4737 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 4738 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); 4739 VdbeCoverage(v); 4740 testcase( regFree1==0 ); 4741 testcase( jumpIfNull==0 ); 4742 } 4743 break; 4744 } 4745 } 4746 sqlite3ReleaseTempReg(pParse, regFree1); 4747 sqlite3ReleaseTempReg(pParse, regFree2); 4748 } 4749 4750 /* 4751 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before 4752 ** code generation, and that copy is deleted after code generation. This 4753 ** ensures that the original pExpr is unchanged. 4754 */ 4755 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ 4756 sqlite3 *db = pParse->db; 4757 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0); 4758 if( db->mallocFailed==0 ){ 4759 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); 4760 } 4761 sqlite3ExprDelete(db, pCopy); 4762 } 4763 4764 /* 4765 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any 4766 ** type of expression. 4767 ** 4768 ** If pExpr is a simple SQL value - an integer, real, string, blob 4769 ** or NULL value - then the VDBE currently being prepared is configured 4770 ** to re-prepare each time a new value is bound to variable pVar. 4771 ** 4772 ** Additionally, if pExpr is a simple SQL value and the value is the 4773 ** same as that currently bound to variable pVar, non-zero is returned. 4774 ** Otherwise, if the values are not the same or if pExpr is not a simple 4775 ** SQL value, zero is returned. 4776 */ 4777 static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){ 4778 int res = 0; 4779 int iVar; 4780 sqlite3_value *pL, *pR = 0; 4781 4782 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR); 4783 if( pR ){ 4784 iVar = pVar->iColumn; 4785 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); 4786 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB); 4787 if( pL ){ 4788 if( sqlite3_value_type(pL)==SQLITE_TEXT ){ 4789 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */ 4790 } 4791 res = 0==sqlite3MemCompare(pL, pR, 0); 4792 } 4793 sqlite3ValueFree(pR); 4794 sqlite3ValueFree(pL); 4795 } 4796 4797 return res; 4798 } 4799 4800 /* 4801 ** Do a deep comparison of two expression trees. Return 0 if the two 4802 ** expressions are completely identical. Return 1 if they differ only 4803 ** by a COLLATE operator at the top level. Return 2 if there are differences 4804 ** other than the top-level COLLATE operator. 4805 ** 4806 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed 4807 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. 4808 ** 4809 ** The pA side might be using TK_REGISTER. If that is the case and pB is 4810 ** not using TK_REGISTER but is otherwise equivalent, then still return 0. 4811 ** 4812 ** Sometimes this routine will return 2 even if the two expressions 4813 ** really are equivalent. If we cannot prove that the expressions are 4814 ** identical, we return 2 just to be safe. So if this routine 4815 ** returns 2, then you do not really know for certain if the two 4816 ** expressions are the same. But if you get a 0 or 1 return, then you 4817 ** can be sure the expressions are the same. In the places where 4818 ** this routine is used, it does not hurt to get an extra 2 - that 4819 ** just might result in some slightly slower code. But returning 4820 ** an incorrect 0 or 1 could lead to a malfunction. 4821 ** 4822 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in 4823 ** pParse->pReprepare can be matched against literals in pB. The 4824 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced. 4825 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in 4826 ** Argument pParse should normally be NULL. If it is not NULL and pA or 4827 ** pB causes a return value of 2. 4828 */ 4829 int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){ 4830 u32 combinedFlags; 4831 if( pA==0 || pB==0 ){ 4832 return pB==pA ? 0 : 2; 4833 } 4834 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){ 4835 return 0; 4836 } 4837 combinedFlags = pA->flags | pB->flags; 4838 if( combinedFlags & EP_IntValue ){ 4839 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){ 4840 return 0; 4841 } 4842 return 2; 4843 } 4844 if( pA->op!=pB->op || pA->op==TK_RAISE ){ 4845 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){ 4846 return 1; 4847 } 4848 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){ 4849 return 1; 4850 } 4851 return 2; 4852 } 4853 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){ 4854 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){ 4855 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; 4856 #ifndef SQLITE_OMIT_WINDOWFUNC 4857 assert( pA->op==pB->op ); 4858 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){ 4859 return 2; 4860 } 4861 if( ExprHasProperty(pA,EP_WinFunc) ){ 4862 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){ 4863 return 2; 4864 } 4865 } 4866 #endif 4867 }else if( pA->op==TK_NULL ){ 4868 return 0; 4869 }else if( pA->op==TK_COLLATE ){ 4870 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; 4871 }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ 4872 return 2; 4873 } 4874 } 4875 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2; 4876 if( (combinedFlags & EP_TokenOnly)==0 ){ 4877 if( combinedFlags & EP_xIsSelect ) return 2; 4878 if( (combinedFlags & EP_FixedCol)==0 4879 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2; 4880 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2; 4881 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; 4882 if( pA->op!=TK_STRING 4883 && pA->op!=TK_TRUEFALSE 4884 && (combinedFlags & EP_Reduced)==0 4885 ){ 4886 if( pA->iColumn!=pB->iColumn ) return 2; 4887 if( pA->op2!=pB->op2 ) return 2; 4888 if( pA->iTable!=pB->iTable 4889 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2; 4890 } 4891 } 4892 return 0; 4893 } 4894 4895 /* 4896 ** Compare two ExprList objects. Return 0 if they are identical and 4897 ** non-zero if they differ in any way. 4898 ** 4899 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed 4900 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. 4901 ** 4902 ** This routine might return non-zero for equivalent ExprLists. The 4903 ** only consequence will be disabled optimizations. But this routine 4904 ** must never return 0 if the two ExprList objects are different, or 4905 ** a malfunction will result. 4906 ** 4907 ** Two NULL pointers are considered to be the same. But a NULL pointer 4908 ** always differs from a non-NULL pointer. 4909 */ 4910 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ 4911 int i; 4912 if( pA==0 && pB==0 ) return 0; 4913 if( pA==0 || pB==0 ) return 1; 4914 if( pA->nExpr!=pB->nExpr ) return 1; 4915 for(i=0; i<pA->nExpr; i++){ 4916 Expr *pExprA = pA->a[i].pExpr; 4917 Expr *pExprB = pB->a[i].pExpr; 4918 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1; 4919 if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1; 4920 } 4921 return 0; 4922 } 4923 4924 /* 4925 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level 4926 ** are ignored. 4927 */ 4928 int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){ 4929 return sqlite3ExprCompare(0, 4930 sqlite3ExprSkipCollate(pA), 4931 sqlite3ExprSkipCollate(pB), 4932 iTab); 4933 } 4934 4935 /* 4936 ** Return non-zero if Expr p can only be true if pNN is not NULL. 4937 */ 4938 static int exprImpliesNotNull( 4939 Parse *pParse, /* Parsing context */ 4940 Expr *p, /* The expression to be checked */ 4941 Expr *pNN, /* The expression that is NOT NULL */ 4942 int iTab, /* Table being evaluated */ 4943 int seenNot /* True if p is an operand of NOT */ 4944 ){ 4945 assert( p ); 4946 assert( pNN ); 4947 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ) return 1; 4948 switch( p->op ){ 4949 case TK_IN: { 4950 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0; 4951 assert( ExprHasProperty(p,EP_xIsSelect) 4952 || (p->x.pList!=0 && p->x.pList->nExpr>0) ); 4953 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); 4954 } 4955 case TK_BETWEEN: { 4956 ExprList *pList = p->x.pList; 4957 assert( pList!=0 ); 4958 assert( pList->nExpr==2 ); 4959 if( seenNot ) return 0; 4960 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, seenNot) 4961 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, seenNot) 4962 ){ 4963 return 1; 4964 } 4965 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); 4966 } 4967 case TK_EQ: 4968 case TK_NE: 4969 case TK_LT: 4970 case TK_LE: 4971 case TK_GT: 4972 case TK_GE: 4973 case TK_PLUS: 4974 case TK_MINUS: 4975 case TK_STAR: 4976 case TK_REM: 4977 case TK_BITAND: 4978 case TK_BITOR: 4979 case TK_SLASH: 4980 case TK_LSHIFT: 4981 case TK_RSHIFT: 4982 case TK_CONCAT: { 4983 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1; 4984 /* Fall thru into the next case */ 4985 } 4986 case TK_SPAN: 4987 case TK_COLLATE: 4988 case TK_BITNOT: 4989 case TK_UPLUS: 4990 case TK_UMINUS: { 4991 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); 4992 } 4993 case TK_TRUTH: { 4994 if( seenNot ) return 0; 4995 if( p->op2!=TK_IS ) return 0; 4996 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); 4997 } 4998 case TK_NOT: { 4999 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 5000 } 5001 } 5002 return 0; 5003 } 5004 5005 /* 5006 ** Return true if we can prove the pE2 will always be true if pE1 is 5007 ** true. Return false if we cannot complete the proof or if pE2 might 5008 ** be false. Examples: 5009 ** 5010 ** pE1: x==5 pE2: x==5 Result: true 5011 ** pE1: x>0 pE2: x==5 Result: false 5012 ** pE1: x=21 pE2: x=21 OR y=43 Result: true 5013 ** pE1: x!=123 pE2: x IS NOT NULL Result: true 5014 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true 5015 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false 5016 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false 5017 ** 5018 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has 5019 ** Expr.iTable<0 then assume a table number given by iTab. 5020 ** 5021 ** If pParse is not NULL, then the values of bound variables in pE1 are 5022 ** compared against literal values in pE2 and pParse->pVdbe->expmask is 5023 ** modified to record which bound variables are referenced. If pParse 5024 ** is NULL, then false will be returned if pE1 contains any bound variables. 5025 ** 5026 ** When in doubt, return false. Returning true might give a performance 5027 ** improvement. Returning false might cause a performance reduction, but 5028 ** it will always give the correct answer and is hence always safe. 5029 */ 5030 int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){ 5031 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){ 5032 return 1; 5033 } 5034 if( pE2->op==TK_OR 5035 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab) 5036 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) ) 5037 ){ 5038 return 1; 5039 } 5040 if( pE2->op==TK_NOTNULL 5041 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0) 5042 ){ 5043 return 1; 5044 } 5045 return 0; 5046 } 5047 5048 /* 5049 ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow(). 5050 ** If the expression node requires that the table at pWalker->iCur 5051 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort. 5052 ** 5053 ** This routine controls an optimization. False positives (setting 5054 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives 5055 ** (never setting pWalker->eCode) is a harmless missed optimization. 5056 */ 5057 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){ 5058 testcase( pExpr->op==TK_AGG_COLUMN ); 5059 testcase( pExpr->op==TK_AGG_FUNCTION ); 5060 if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune; 5061 switch( pExpr->op ){ 5062 case TK_ISNOT: 5063 case TK_NOT: 5064 case TK_ISNULL: 5065 case TK_NOTNULL: 5066 case TK_IS: 5067 case TK_OR: 5068 case TK_CASE: 5069 case TK_IN: 5070 case TK_FUNCTION: 5071 testcase( pExpr->op==TK_ISNOT ); 5072 testcase( pExpr->op==TK_NOT ); 5073 testcase( pExpr->op==TK_ISNULL ); 5074 testcase( pExpr->op==TK_NOTNULL ); 5075 testcase( pExpr->op==TK_IS ); 5076 testcase( pExpr->op==TK_OR ); 5077 testcase( pExpr->op==TK_CASE ); 5078 testcase( pExpr->op==TK_IN ); 5079 testcase( pExpr->op==TK_FUNCTION ); 5080 return WRC_Prune; 5081 case TK_COLUMN: 5082 if( pWalker->u.iCur==pExpr->iTable ){ 5083 pWalker->eCode = 1; 5084 return WRC_Abort; 5085 } 5086 return WRC_Prune; 5087 5088 /* Virtual tables are allowed to use constraints like x=NULL. So 5089 ** a term of the form x=y does not prove that y is not null if x 5090 ** is the column of a virtual table */ 5091 case TK_EQ: 5092 case TK_NE: 5093 case TK_LT: 5094 case TK_LE: 5095 case TK_GT: 5096 case TK_GE: 5097 testcase( pExpr->op==TK_EQ ); 5098 testcase( pExpr->op==TK_NE ); 5099 testcase( pExpr->op==TK_LT ); 5100 testcase( pExpr->op==TK_LE ); 5101 testcase( pExpr->op==TK_GT ); 5102 testcase( pExpr->op==TK_GE ); 5103 if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->y.pTab)) 5104 || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->y.pTab)) 5105 ){ 5106 return WRC_Prune; 5107 } 5108 default: 5109 return WRC_Continue; 5110 } 5111 } 5112 5113 /* 5114 ** Return true (non-zero) if expression p can only be true if at least 5115 ** one column of table iTab is non-null. In other words, return true 5116 ** if expression p will always be NULL or false if every column of iTab 5117 ** is NULL. 5118 ** 5119 ** False negatives are acceptable. In other words, it is ok to return 5120 ** zero even if expression p will never be true of every column of iTab 5121 ** is NULL. A false negative is merely a missed optimization opportunity. 5122 ** 5123 ** False positives are not allowed, however. A false positive may result 5124 ** in an incorrect answer. 5125 ** 5126 ** Terms of p that are marked with EP_FromJoin (and hence that come from 5127 ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis. 5128 ** 5129 ** This routine is used to check if a LEFT JOIN can be converted into 5130 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE 5131 ** clause requires that some column of the right table of the LEFT JOIN 5132 ** be non-NULL, then the LEFT JOIN can be safely converted into an 5133 ** ordinary join. 5134 */ 5135 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){ 5136 Walker w; 5137 p = sqlite3ExprSkipCollate(p); 5138 while( p ){ 5139 if( p->op==TK_NOTNULL ){ 5140 p = p->pLeft; 5141 }else if( p->op==TK_AND ){ 5142 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1; 5143 p = p->pRight; 5144 }else{ 5145 break; 5146 } 5147 } 5148 w.xExprCallback = impliesNotNullRow; 5149 w.xSelectCallback = 0; 5150 w.xSelectCallback2 = 0; 5151 w.eCode = 0; 5152 w.u.iCur = iTab; 5153 sqlite3WalkExpr(&w, p); 5154 return w.eCode; 5155 } 5156 5157 /* 5158 ** An instance of the following structure is used by the tree walker 5159 ** to determine if an expression can be evaluated by reference to the 5160 ** index only, without having to do a search for the corresponding 5161 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur 5162 ** is the cursor for the table. 5163 */ 5164 struct IdxCover { 5165 Index *pIdx; /* The index to be tested for coverage */ 5166 int iCur; /* Cursor number for the table corresponding to the index */ 5167 }; 5168 5169 /* 5170 ** Check to see if there are references to columns in table 5171 ** pWalker->u.pIdxCover->iCur can be satisfied using the index 5172 ** pWalker->u.pIdxCover->pIdx. 5173 */ 5174 static int exprIdxCover(Walker *pWalker, Expr *pExpr){ 5175 if( pExpr->op==TK_COLUMN 5176 && pExpr->iTable==pWalker->u.pIdxCover->iCur 5177 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 5178 ){ 5179 pWalker->eCode = 1; 5180 return WRC_Abort; 5181 } 5182 return WRC_Continue; 5183 } 5184 5185 /* 5186 ** Determine if an index pIdx on table with cursor iCur contains will 5187 ** the expression pExpr. Return true if the index does cover the 5188 ** expression and false if the pExpr expression references table columns 5189 ** that are not found in the index pIdx. 5190 ** 5191 ** An index covering an expression means that the expression can be 5192 ** evaluated using only the index and without having to lookup the 5193 ** corresponding table entry. 5194 */ 5195 int sqlite3ExprCoveredByIndex( 5196 Expr *pExpr, /* The index to be tested */ 5197 int iCur, /* The cursor number for the corresponding table */ 5198 Index *pIdx /* The index that might be used for coverage */ 5199 ){ 5200 Walker w; 5201 struct IdxCover xcov; 5202 memset(&w, 0, sizeof(w)); 5203 xcov.iCur = iCur; 5204 xcov.pIdx = pIdx; 5205 w.xExprCallback = exprIdxCover; 5206 w.u.pIdxCover = &xcov; 5207 sqlite3WalkExpr(&w, pExpr); 5208 return !w.eCode; 5209 } 5210 5211 5212 /* 5213 ** An instance of the following structure is used by the tree walker 5214 ** to count references to table columns in the arguments of an 5215 ** aggregate function, in order to implement the 5216 ** sqlite3FunctionThisSrc() routine. 5217 */ 5218 struct SrcCount { 5219 SrcList *pSrc; /* One particular FROM clause in a nested query */ 5220 int nThis; /* Number of references to columns in pSrcList */ 5221 int nOther; /* Number of references to columns in other FROM clauses */ 5222 }; 5223 5224 /* 5225 ** Count the number of references to columns. 5226 */ 5227 static int exprSrcCount(Walker *pWalker, Expr *pExpr){ 5228 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc() 5229 ** is always called before sqlite3ExprAnalyzeAggregates() and so the 5230 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If 5231 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the 5232 ** NEVER() will need to be removed. */ 5233 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){ 5234 int i; 5235 struct SrcCount *p = pWalker->u.pSrcCount; 5236 SrcList *pSrc = p->pSrc; 5237 int nSrc = pSrc ? pSrc->nSrc : 0; 5238 for(i=0; i<nSrc; i++){ 5239 if( pExpr->iTable==pSrc->a[i].iCursor ) break; 5240 } 5241 if( i<nSrc ){ 5242 p->nThis++; 5243 }else{ 5244 p->nOther++; 5245 } 5246 } 5247 return WRC_Continue; 5248 } 5249 5250 /* 5251 ** Determine if any of the arguments to the pExpr Function reference 5252 ** pSrcList. Return true if they do. Also return true if the function 5253 ** has no arguments or has only constant arguments. Return false if pExpr 5254 ** references columns but not columns of tables found in pSrcList. 5255 */ 5256 int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ 5257 Walker w; 5258 struct SrcCount cnt; 5259 assert( pExpr->op==TK_AGG_FUNCTION ); 5260 w.xExprCallback = exprSrcCount; 5261 w.xSelectCallback = 0; 5262 w.u.pSrcCount = &cnt; 5263 cnt.pSrc = pSrcList; 5264 cnt.nThis = 0; 5265 cnt.nOther = 0; 5266 sqlite3WalkExprList(&w, pExpr->x.pList); 5267 return cnt.nThis>0 || cnt.nOther==0; 5268 } 5269 5270 /* 5271 ** Add a new element to the pAggInfo->aCol[] array. Return the index of 5272 ** the new element. Return a negative number if malloc fails. 5273 */ 5274 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ 5275 int i; 5276 pInfo->aCol = sqlite3ArrayAllocate( 5277 db, 5278 pInfo->aCol, 5279 sizeof(pInfo->aCol[0]), 5280 &pInfo->nColumn, 5281 &i 5282 ); 5283 return i; 5284 } 5285 5286 /* 5287 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of 5288 ** the new element. Return a negative number if malloc fails. 5289 */ 5290 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ 5291 int i; 5292 pInfo->aFunc = sqlite3ArrayAllocate( 5293 db, 5294 pInfo->aFunc, 5295 sizeof(pInfo->aFunc[0]), 5296 &pInfo->nFunc, 5297 &i 5298 ); 5299 return i; 5300 } 5301 5302 /* 5303 ** This is the xExprCallback for a tree walker. It is used to 5304 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates 5305 ** for additional information. 5306 */ 5307 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ 5308 int i; 5309 NameContext *pNC = pWalker->u.pNC; 5310 Parse *pParse = pNC->pParse; 5311 SrcList *pSrcList = pNC->pSrcList; 5312 AggInfo *pAggInfo = pNC->uNC.pAggInfo; 5313 5314 assert( pNC->ncFlags & NC_UAggInfo ); 5315 switch( pExpr->op ){ 5316 case TK_AGG_COLUMN: 5317 case TK_COLUMN: { 5318 testcase( pExpr->op==TK_AGG_COLUMN ); 5319 testcase( pExpr->op==TK_COLUMN ); 5320 /* Check to see if the column is in one of the tables in the FROM 5321 ** clause of the aggregate query */ 5322 if( ALWAYS(pSrcList!=0) ){ 5323 struct SrcList_item *pItem = pSrcList->a; 5324 for(i=0; i<pSrcList->nSrc; i++, pItem++){ 5325 struct AggInfo_col *pCol; 5326 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 5327 if( pExpr->iTable==pItem->iCursor ){ 5328 /* If we reach this point, it means that pExpr refers to a table 5329 ** that is in the FROM clause of the aggregate query. 5330 ** 5331 ** Make an entry for the column in pAggInfo->aCol[] if there 5332 ** is not an entry there already. 5333 */ 5334 int k; 5335 pCol = pAggInfo->aCol; 5336 for(k=0; k<pAggInfo->nColumn; k++, pCol++){ 5337 if( pCol->iTable==pExpr->iTable && 5338 pCol->iColumn==pExpr->iColumn ){ 5339 break; 5340 } 5341 } 5342 if( (k>=pAggInfo->nColumn) 5343 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 5344 ){ 5345 pCol = &pAggInfo->aCol[k]; 5346 pCol->pTab = pExpr->y.pTab; 5347 pCol->iTable = pExpr->iTable; 5348 pCol->iColumn = pExpr->iColumn; 5349 pCol->iMem = ++pParse->nMem; 5350 pCol->iSorterColumn = -1; 5351 pCol->pExpr = pExpr; 5352 if( pAggInfo->pGroupBy ){ 5353 int j, n; 5354 ExprList *pGB = pAggInfo->pGroupBy; 5355 struct ExprList_item *pTerm = pGB->a; 5356 n = pGB->nExpr; 5357 for(j=0; j<n; j++, pTerm++){ 5358 Expr *pE = pTerm->pExpr; 5359 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && 5360 pE->iColumn==pExpr->iColumn ){ 5361 pCol->iSorterColumn = j; 5362 break; 5363 } 5364 } 5365 } 5366 if( pCol->iSorterColumn<0 ){ 5367 pCol->iSorterColumn = pAggInfo->nSortingColumn++; 5368 } 5369 } 5370 /* There is now an entry for pExpr in pAggInfo->aCol[] (either 5371 ** because it was there before or because we just created it). 5372 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that 5373 ** pAggInfo->aCol[] entry. 5374 */ 5375 ExprSetVVAProperty(pExpr, EP_NoReduce); 5376 pExpr->pAggInfo = pAggInfo; 5377 pExpr->op = TK_AGG_COLUMN; 5378 pExpr->iAgg = (i16)k; 5379 break; 5380 } /* endif pExpr->iTable==pItem->iCursor */ 5381 } /* end loop over pSrcList */ 5382 } 5383 return WRC_Prune; 5384 } 5385 case TK_AGG_FUNCTION: { 5386 if( (pNC->ncFlags & NC_InAggFunc)==0 5387 && pWalker->walkerDepth==pExpr->op2 5388 ){ 5389 /* Check to see if pExpr is a duplicate of another aggregate 5390 ** function that is already in the pAggInfo structure 5391 */ 5392 struct AggInfo_func *pItem = pAggInfo->aFunc; 5393 for(i=0; i<pAggInfo->nFunc; i++, pItem++){ 5394 if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){ 5395 break; 5396 } 5397 } 5398 if( i>=pAggInfo->nFunc ){ 5399 /* pExpr is original. Make a new entry in pAggInfo->aFunc[] 5400 */ 5401 u8 enc = ENC(pParse->db); 5402 i = addAggInfoFunc(pParse->db, pAggInfo); 5403 if( i>=0 ){ 5404 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 5405 pItem = &pAggInfo->aFunc[i]; 5406 pItem->pExpr = pExpr; 5407 pItem->iMem = ++pParse->nMem; 5408 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5409 pItem->pFunc = sqlite3FindFunction(pParse->db, 5410 pExpr->u.zToken, 5411 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); 5412 if( pExpr->flags & EP_Distinct ){ 5413 pItem->iDistinct = pParse->nTab++; 5414 }else{ 5415 pItem->iDistinct = -1; 5416 } 5417 } 5418 } 5419 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry 5420 */ 5421 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 5422 ExprSetVVAProperty(pExpr, EP_NoReduce); 5423 pExpr->iAgg = (i16)i; 5424 pExpr->pAggInfo = pAggInfo; 5425 return WRC_Prune; 5426 }else{ 5427 return WRC_Continue; 5428 } 5429 } 5430 } 5431 return WRC_Continue; 5432 } 5433 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ 5434 UNUSED_PARAMETER(pSelect); 5435 pWalker->walkerDepth++; 5436 return WRC_Continue; 5437 } 5438 static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){ 5439 UNUSED_PARAMETER(pSelect); 5440 pWalker->walkerDepth--; 5441 } 5442 5443 /* 5444 ** Analyze the pExpr expression looking for aggregate functions and 5445 ** for variables that need to be added to AggInfo object that pNC->pAggInfo 5446 ** points to. Additional entries are made on the AggInfo object as 5447 ** necessary. 5448 ** 5449 ** This routine should only be called after the expression has been 5450 ** analyzed by sqlite3ResolveExprNames(). 5451 */ 5452 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ 5453 Walker w; 5454 w.xExprCallback = analyzeAggregate; 5455 w.xSelectCallback = analyzeAggregatesInSelect; 5456 w.xSelectCallback2 = analyzeAggregatesInSelectEnd; 5457 w.walkerDepth = 0; 5458 w.u.pNC = pNC; 5459 w.pParse = 0; 5460 assert( pNC->pSrcList!=0 ); 5461 sqlite3WalkExpr(&w, pExpr); 5462 } 5463 5464 /* 5465 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an 5466 ** expression list. Return the number of errors. 5467 ** 5468 ** If an error is found, the analysis is cut short. 5469 */ 5470 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ 5471 struct ExprList_item *pItem; 5472 int i; 5473 if( pList ){ 5474 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ 5475 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); 5476 } 5477 } 5478 } 5479 5480 /* 5481 ** Allocate a single new register for use to hold some intermediate result. 5482 */ 5483 int sqlite3GetTempReg(Parse *pParse){ 5484 if( pParse->nTempReg==0 ){ 5485 return ++pParse->nMem; 5486 } 5487 return pParse->aTempReg[--pParse->nTempReg]; 5488 } 5489 5490 /* 5491 ** Deallocate a register, making available for reuse for some other 5492 ** purpose. 5493 */ 5494 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ 5495 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){ 5496 pParse->aTempReg[pParse->nTempReg++] = iReg; 5497 } 5498 } 5499 5500 /* 5501 ** Allocate or deallocate a block of nReg consecutive registers. 5502 */ 5503 int sqlite3GetTempRange(Parse *pParse, int nReg){ 5504 int i, n; 5505 if( nReg==1 ) return sqlite3GetTempReg(pParse); 5506 i = pParse->iRangeReg; 5507 n = pParse->nRangeReg; 5508 if( nReg<=n ){ 5509 pParse->iRangeReg += nReg; 5510 pParse->nRangeReg -= nReg; 5511 }else{ 5512 i = pParse->nMem+1; 5513 pParse->nMem += nReg; 5514 } 5515 return i; 5516 } 5517 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ 5518 if( nReg==1 ){ 5519 sqlite3ReleaseTempReg(pParse, iReg); 5520 return; 5521 } 5522 if( nReg>pParse->nRangeReg ){ 5523 pParse->nRangeReg = nReg; 5524 pParse->iRangeReg = iReg; 5525 } 5526 } 5527 5528 /* 5529 ** Mark all temporary registers as being unavailable for reuse. 5530 */ 5531 void sqlite3ClearTempRegCache(Parse *pParse){ 5532 pParse->nTempReg = 0; 5533 pParse->nRangeReg = 0; 5534 } 5535 5536 /* 5537 ** Validate that no temporary register falls within the range of 5538 ** iFirst..iLast, inclusive. This routine is only call from within assert() 5539 ** statements. 5540 */ 5541 #ifdef SQLITE_DEBUG 5542 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ 5543 int i; 5544 if( pParse->nRangeReg>0 5545 && pParse->iRangeReg+pParse->nRangeReg > iFirst 5546 && pParse->iRangeReg <= iLast 5547 ){ 5548 return 0; 5549 } 5550 for(i=0; i<pParse->nTempReg; i++){ 5551 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){ 5552 return 0; 5553 } 5554 } 5555 return 1; 5556 } 5557 #endif /* SQLITE_DEBUG */ 5558