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