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 /* 18 ** Return the 'affinity' of the expression pExpr if any. 19 ** 20 ** If pExpr is a column, a reference to a column via an 'AS' alias, 21 ** or a sub-select with a column as the return value, then the 22 ** affinity of that column is returned. Otherwise, 0x00 is returned, 23 ** indicating no affinity for the expression. 24 ** 25 ** i.e. the WHERE clause expresssions in the following statements all 26 ** have an affinity: 27 ** 28 ** CREATE TABLE t1(a); 29 ** SELECT * FROM t1 WHERE a; 30 ** SELECT a AS b FROM t1 WHERE b; 31 ** SELECT * FROM t1 WHERE (select a from t1); 32 */ 33 char sqlite3ExprAffinity(Expr *pExpr){ 34 int op = pExpr->op; 35 if( op==TK_SELECT ){ 36 assert( pExpr->flags&EP_xIsSelect ); 37 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); 38 } 39 #ifndef SQLITE_OMIT_CAST 40 if( op==TK_CAST ){ 41 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 42 return sqlite3AffinityType(pExpr->u.zToken); 43 } 44 #endif 45 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 46 && pExpr->pTab!=0 47 ){ 48 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally 49 ** a TK_COLUMN but was previously evaluated and cached in a register */ 50 int j = pExpr->iColumn; 51 if( j<0 ) return SQLITE_AFF_INTEGER; 52 assert( pExpr->pTab && j<pExpr->pTab->nCol ); 53 return pExpr->pTab->aCol[j].affinity; 54 } 55 return pExpr->affinity; 56 } 57 58 /* 59 ** Set the collating sequence for expression pExpr to be the collating 60 ** sequence named by pToken. Return a pointer to the revised expression. 61 ** The collating sequence is marked as "explicit" using the EP_ExpCollate 62 ** flag. An explicit collating sequence will override implicit 63 ** collating sequences. 64 */ 65 Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){ 66 char *zColl = 0; /* Dequoted name of collation sequence */ 67 CollSeq *pColl; 68 sqlite3 *db = pParse->db; 69 zColl = sqlite3NameFromToken(db, pCollName); 70 if( pExpr && zColl ){ 71 pColl = sqlite3LocateCollSeq(pParse, zColl); 72 if( pColl ){ 73 pExpr->pColl = pColl; 74 pExpr->flags |= EP_ExpCollate; 75 } 76 } 77 sqlite3DbFree(db, zColl); 78 return pExpr; 79 } 80 81 /* 82 ** Return the default collation sequence for the expression pExpr. If 83 ** there is no default collation type, return 0. 84 */ 85 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ 86 CollSeq *pColl = 0; 87 Expr *p = pExpr; 88 while( ALWAYS(p) ){ 89 int op; 90 pColl = p->pColl; 91 if( pColl ) break; 92 op = p->op; 93 if( p->pTab!=0 && ( 94 op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER 95 )){ 96 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally 97 ** a TK_COLUMN but was previously evaluated and cached in a register */ 98 const char *zColl; 99 int j = p->iColumn; 100 if( j>=0 ){ 101 sqlite3 *db = pParse->db; 102 zColl = p->pTab->aCol[j].zColl; 103 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 104 pExpr->pColl = pColl; 105 } 106 break; 107 } 108 if( op!=TK_CAST && op!=TK_UPLUS ){ 109 break; 110 } 111 p = p->pLeft; 112 } 113 if( sqlite3CheckCollSeq(pParse, pColl) ){ 114 pColl = 0; 115 } 116 return pColl; 117 } 118 119 /* 120 ** pExpr is an operand of a comparison operator. aff2 is the 121 ** type affinity of the other operand. This routine returns the 122 ** type affinity that should be used for the comparison operator. 123 */ 124 char sqlite3CompareAffinity(Expr *pExpr, char aff2){ 125 char aff1 = sqlite3ExprAffinity(pExpr); 126 if( aff1 && aff2 ){ 127 /* Both sides of the comparison are columns. If one has numeric 128 ** affinity, use that. Otherwise use no affinity. 129 */ 130 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ 131 return SQLITE_AFF_NUMERIC; 132 }else{ 133 return SQLITE_AFF_NONE; 134 } 135 }else if( !aff1 && !aff2 ){ 136 /* Neither side of the comparison is a column. Compare the 137 ** results directly. 138 */ 139 return SQLITE_AFF_NONE; 140 }else{ 141 /* One side is a column, the other is not. Use the columns affinity. */ 142 assert( aff1==0 || aff2==0 ); 143 return (aff1 + aff2); 144 } 145 } 146 147 /* 148 ** pExpr is a comparison operator. Return the type affinity that should 149 ** be applied to both operands prior to doing the comparison. 150 */ 151 static char comparisonAffinity(Expr *pExpr){ 152 char aff; 153 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || 154 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || 155 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); 156 assert( pExpr->pLeft ); 157 aff = sqlite3ExprAffinity(pExpr->pLeft); 158 if( pExpr->pRight ){ 159 aff = sqlite3CompareAffinity(pExpr->pRight, aff); 160 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 161 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); 162 }else if( !aff ){ 163 aff = SQLITE_AFF_NONE; 164 } 165 return aff; 166 } 167 168 /* 169 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. 170 ** idx_affinity is the affinity of an indexed column. Return true 171 ** if the index with affinity idx_affinity may be used to implement 172 ** the comparison in pExpr. 173 */ 174 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ 175 char aff = comparisonAffinity(pExpr); 176 switch( aff ){ 177 case SQLITE_AFF_NONE: 178 return 1; 179 case SQLITE_AFF_TEXT: 180 return idx_affinity==SQLITE_AFF_TEXT; 181 default: 182 return sqlite3IsNumericAffinity(idx_affinity); 183 } 184 } 185 186 /* 187 ** Return the P5 value that should be used for a binary comparison 188 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. 189 */ 190 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ 191 u8 aff = (char)sqlite3ExprAffinity(pExpr2); 192 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; 193 return aff; 194 } 195 196 /* 197 ** Return a pointer to the collation sequence that should be used by 198 ** a binary comparison operator comparing pLeft and pRight. 199 ** 200 ** If the left hand expression has a collating sequence type, then it is 201 ** used. Otherwise the collation sequence for the right hand expression 202 ** is used, or the default (BINARY) if neither expression has a collating 203 ** type. 204 ** 205 ** Argument pRight (but not pLeft) may be a null pointer. In this case, 206 ** it is not considered. 207 */ 208 CollSeq *sqlite3BinaryCompareCollSeq( 209 Parse *pParse, 210 Expr *pLeft, 211 Expr *pRight 212 ){ 213 CollSeq *pColl; 214 assert( pLeft ); 215 if( pLeft->flags & EP_ExpCollate ){ 216 assert( pLeft->pColl ); 217 pColl = pLeft->pColl; 218 }else if( pRight && pRight->flags & EP_ExpCollate ){ 219 assert( pRight->pColl ); 220 pColl = pRight->pColl; 221 }else{ 222 pColl = sqlite3ExprCollSeq(pParse, pLeft); 223 if( !pColl ){ 224 pColl = sqlite3ExprCollSeq(pParse, pRight); 225 } 226 } 227 return pColl; 228 } 229 230 /* 231 ** Generate code for a comparison operator. 232 */ 233 static int codeCompare( 234 Parse *pParse, /* The parsing (and code generating) context */ 235 Expr *pLeft, /* The left operand */ 236 Expr *pRight, /* The right operand */ 237 int opcode, /* The comparison opcode */ 238 int in1, int in2, /* Register holding operands */ 239 int dest, /* Jump here if true. */ 240 int jumpIfNull /* If true, jump if either operand is NULL */ 241 ){ 242 int p5; 243 int addr; 244 CollSeq *p4; 245 246 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); 247 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); 248 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, 249 (void*)p4, P4_COLLSEQ); 250 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); 251 return addr; 252 } 253 254 #if SQLITE_MAX_EXPR_DEPTH>0 255 /* 256 ** Check that argument nHeight is less than or equal to the maximum 257 ** expression depth allowed. If it is not, leave an error message in 258 ** pParse. 259 */ 260 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ 261 int rc = SQLITE_OK; 262 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; 263 if( nHeight>mxHeight ){ 264 sqlite3ErrorMsg(pParse, 265 "Expression tree is too large (maximum depth %d)", mxHeight 266 ); 267 rc = SQLITE_ERROR; 268 } 269 return rc; 270 } 271 272 /* The following three functions, heightOfExpr(), heightOfExprList() 273 ** and heightOfSelect(), are used to determine the maximum height 274 ** of any expression tree referenced by the structure passed as the 275 ** first argument. 276 ** 277 ** If this maximum height is greater than the current value pointed 278 ** to by pnHeight, the second parameter, then set *pnHeight to that 279 ** value. 280 */ 281 static void heightOfExpr(Expr *p, int *pnHeight){ 282 if( p ){ 283 if( p->nHeight>*pnHeight ){ 284 *pnHeight = p->nHeight; 285 } 286 } 287 } 288 static void heightOfExprList(ExprList *p, int *pnHeight){ 289 if( p ){ 290 int i; 291 for(i=0; i<p->nExpr; i++){ 292 heightOfExpr(p->a[i].pExpr, pnHeight); 293 } 294 } 295 } 296 static void heightOfSelect(Select *p, int *pnHeight){ 297 if( p ){ 298 heightOfExpr(p->pWhere, pnHeight); 299 heightOfExpr(p->pHaving, pnHeight); 300 heightOfExpr(p->pLimit, pnHeight); 301 heightOfExpr(p->pOffset, pnHeight); 302 heightOfExprList(p->pEList, pnHeight); 303 heightOfExprList(p->pGroupBy, pnHeight); 304 heightOfExprList(p->pOrderBy, pnHeight); 305 heightOfSelect(p->pPrior, pnHeight); 306 } 307 } 308 309 /* 310 ** Set the Expr.nHeight variable in the structure passed as an 311 ** argument. An expression with no children, Expr.pList or 312 ** Expr.pSelect member has a height of 1. Any other expression 313 ** has a height equal to the maximum height of any other 314 ** referenced Expr plus one. 315 */ 316 static void exprSetHeight(Expr *p){ 317 int nHeight = 0; 318 heightOfExpr(p->pLeft, &nHeight); 319 heightOfExpr(p->pRight, &nHeight); 320 if( ExprHasProperty(p, EP_xIsSelect) ){ 321 heightOfSelect(p->x.pSelect, &nHeight); 322 }else{ 323 heightOfExprList(p->x.pList, &nHeight); 324 } 325 p->nHeight = nHeight + 1; 326 } 327 328 /* 329 ** Set the Expr.nHeight variable using the exprSetHeight() function. If 330 ** the height is greater than the maximum allowed expression depth, 331 ** leave an error in pParse. 332 */ 333 void sqlite3ExprSetHeight(Parse *pParse, Expr *p){ 334 exprSetHeight(p); 335 sqlite3ExprCheckHeight(pParse, p->nHeight); 336 } 337 338 /* 339 ** Return the maximum height of any expression tree referenced 340 ** by the select statement passed as an argument. 341 */ 342 int sqlite3SelectExprHeight(Select *p){ 343 int nHeight = 0; 344 heightOfSelect(p, &nHeight); 345 return nHeight; 346 } 347 #else 348 #define exprSetHeight(y) 349 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */ 350 351 /* 352 ** This routine is the core allocator for Expr nodes. 353 ** 354 ** Construct a new expression node and return a pointer to it. Memory 355 ** for this node and for the pToken argument is a single allocation 356 ** obtained from sqlite3DbMalloc(). The calling function 357 ** is responsible for making sure the node eventually gets freed. 358 ** 359 ** If dequote is true, then the token (if it exists) is dequoted. 360 ** If dequote is false, no dequoting is performance. The deQuote 361 ** parameter is ignored if pToken is NULL or if the token does not 362 ** appear to be quoted. If the quotes were of the form "..." (double-quotes) 363 ** then the EP_DblQuoted flag is set on the expression node. 364 ** 365 ** Special case: If op==TK_INTEGER and pToken points to a string that 366 ** can be translated into a 32-bit integer, then the token is not 367 ** stored in u.zToken. Instead, the integer values is written 368 ** into u.iValue and the EP_IntValue flag is set. No extra storage 369 ** is allocated to hold the integer text and the dequote flag is ignored. 370 */ 371 Expr *sqlite3ExprAlloc( 372 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ 373 int op, /* Expression opcode */ 374 const Token *pToken, /* Token argument. Might be NULL */ 375 int dequote /* True to dequote */ 376 ){ 377 Expr *pNew; 378 int nExtra = 0; 379 int iValue = 0; 380 381 if( pToken ){ 382 if( op!=TK_INTEGER || pToken->z==0 383 || sqlite3GetInt32(pToken->z, &iValue)==0 ){ 384 nExtra = pToken->n+1; 385 } 386 } 387 pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra); 388 if( pNew ){ 389 pNew->op = (u8)op; 390 pNew->iAgg = -1; 391 if( pToken ){ 392 if( nExtra==0 ){ 393 pNew->flags |= EP_IntValue; 394 pNew->u.iValue = iValue; 395 }else{ 396 int c; 397 pNew->u.zToken = (char*)&pNew[1]; 398 memcpy(pNew->u.zToken, pToken->z, pToken->n); 399 pNew->u.zToken[pToken->n] = 0; 400 if( dequote && nExtra>=3 401 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){ 402 sqlite3Dequote(pNew->u.zToken); 403 if( c=='"' ) pNew->flags |= EP_DblQuoted; 404 } 405 } 406 } 407 #if SQLITE_MAX_EXPR_DEPTH>0 408 pNew->nHeight = 1; 409 #endif 410 } 411 return pNew; 412 } 413 414 /* 415 ** Allocate a new expression node from a zero-terminated token that has 416 ** already been dequoted. 417 */ 418 Expr *sqlite3Expr( 419 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ 420 int op, /* Expression opcode */ 421 const char *zToken /* Token argument. Might be NULL */ 422 ){ 423 Token x; 424 x.z = zToken; 425 x.n = zToken ? sqlite3Strlen30(zToken) : 0; 426 return sqlite3ExprAlloc(db, op, &x, 0); 427 } 428 429 /* 430 ** Attach subtrees pLeft and pRight to the Expr node pRoot. 431 ** 432 ** If pRoot==NULL that means that a memory allocation error has occurred. 433 ** In that case, delete the subtrees pLeft and pRight. 434 */ 435 void sqlite3ExprAttachSubtrees( 436 sqlite3 *db, 437 Expr *pRoot, 438 Expr *pLeft, 439 Expr *pRight 440 ){ 441 if( pRoot==0 ){ 442 assert( db->mallocFailed ); 443 sqlite3ExprDelete(db, pLeft); 444 sqlite3ExprDelete(db, pRight); 445 }else{ 446 if( pRight ){ 447 pRoot->pRight = pRight; 448 if( pRight->flags & EP_ExpCollate ){ 449 pRoot->flags |= EP_ExpCollate; 450 pRoot->pColl = pRight->pColl; 451 } 452 } 453 if( pLeft ){ 454 pRoot->pLeft = pLeft; 455 if( pLeft->flags & EP_ExpCollate ){ 456 pRoot->flags |= EP_ExpCollate; 457 pRoot->pColl = pLeft->pColl; 458 } 459 } 460 exprSetHeight(pRoot); 461 } 462 } 463 464 /* 465 ** Allocate a Expr node which joins as many as two subtrees. 466 ** 467 ** One or both of the subtrees can be NULL. Return a pointer to the new 468 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, 469 ** free the subtrees and return NULL. 470 */ 471 Expr *sqlite3PExpr( 472 Parse *pParse, /* Parsing context */ 473 int op, /* Expression opcode */ 474 Expr *pLeft, /* Left operand */ 475 Expr *pRight, /* Right operand */ 476 const Token *pToken /* Argument token */ 477 ){ 478 Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1); 479 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); 480 return p; 481 } 482 483 /* 484 ** Join two expressions using an AND operator. If either expression is 485 ** NULL, then just return the other expression. 486 */ 487 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){ 488 if( pLeft==0 ){ 489 return pRight; 490 }else if( pRight==0 ){ 491 return pLeft; 492 }else{ 493 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0); 494 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight); 495 return pNew; 496 } 497 } 498 499 /* 500 ** Construct a new expression node for a function with multiple 501 ** arguments. 502 */ 503 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){ 504 Expr *pNew; 505 sqlite3 *db = pParse->db; 506 assert( pToken ); 507 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); 508 if( pNew==0 ){ 509 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ 510 return 0; 511 } 512 pNew->x.pList = pList; 513 assert( !ExprHasProperty(pNew, EP_xIsSelect) ); 514 sqlite3ExprSetHeight(pParse, pNew); 515 return pNew; 516 } 517 518 /* 519 ** Assign a variable number to an expression that encodes a wildcard 520 ** in the original SQL statement. 521 ** 522 ** Wildcards consisting of a single "?" are assigned the next sequential 523 ** variable number. 524 ** 525 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make 526 ** sure "nnn" is not too be to avoid a denial of service attack when 527 ** the SQL statement comes from an external source. 528 ** 529 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number 530 ** as the previous instance of the same wildcard. Or if this is the first 531 ** instance of the wildcard, the next sequenial variable number is 532 ** assigned. 533 */ 534 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){ 535 sqlite3 *db = pParse->db; 536 const char *z; 537 538 if( pExpr==0 ) return; 539 assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); 540 z = pExpr->u.zToken; 541 assert( z!=0 ); 542 assert( z[0]!=0 ); 543 if( z[1]==0 ){ 544 /* Wildcard of the form "?". Assign the next variable number */ 545 assert( z[0]=='?' ); 546 pExpr->iColumn = (ynVar)(++pParse->nVar); 547 }else if( z[0]=='?' ){ 548 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and 549 ** use it as the variable number */ 550 int i = atoi((char*)&z[1]); 551 pExpr->iColumn = (ynVar)i; 552 testcase( i==0 ); 553 testcase( i==1 ); 554 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); 555 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); 556 if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 557 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", 558 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); 559 } 560 if( i>pParse->nVar ){ 561 pParse->nVar = i; 562 } 563 }else{ 564 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable 565 ** number as the prior appearance of the same name, or if the name 566 ** has never appeared before, reuse the same variable number 567 */ 568 int i; 569 u32 n; 570 n = sqlite3Strlen30(z); 571 for(i=0; i<pParse->nVarExpr; i++){ 572 Expr *pE = pParse->apVarExpr[i]; 573 assert( pE!=0 ); 574 if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){ 575 pExpr->iColumn = pE->iColumn; 576 break; 577 } 578 } 579 if( i>=pParse->nVarExpr ){ 580 pExpr->iColumn = (ynVar)(++pParse->nVar); 581 if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){ 582 pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10; 583 pParse->apVarExpr = 584 sqlite3DbReallocOrFree( 585 db, 586 pParse->apVarExpr, 587 pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) 588 ); 589 } 590 if( !db->mallocFailed ){ 591 assert( pParse->apVarExpr!=0 ); 592 pParse->apVarExpr[pParse->nVarExpr++] = pExpr; 593 } 594 } 595 } 596 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 597 sqlite3ErrorMsg(pParse, "too many SQL variables"); 598 } 599 } 600 601 /* 602 ** Recursively delete an expression tree. 603 */ 604 void sqlite3ExprDelete(sqlite3 *db, Expr *p){ 605 if( p==0 ) return; 606 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){ 607 sqlite3ExprDelete(db, p->pLeft); 608 sqlite3ExprDelete(db, p->pRight); 609 if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){ 610 sqlite3DbFree(db, p->u.zToken); 611 } 612 if( ExprHasProperty(p, EP_xIsSelect) ){ 613 sqlite3SelectDelete(db, p->x.pSelect); 614 }else{ 615 sqlite3ExprListDelete(db, p->x.pList); 616 } 617 } 618 if( !ExprHasProperty(p, EP_Static) ){ 619 sqlite3DbFree(db, p); 620 } 621 } 622 623 /* 624 ** Return the number of bytes allocated for the expression structure 625 ** passed as the first argument. This is always one of EXPR_FULLSIZE, 626 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. 627 */ 628 static int exprStructSize(Expr *p){ 629 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; 630 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; 631 return EXPR_FULLSIZE; 632 } 633 634 /* 635 ** The dupedExpr*Size() routines each return the number of bytes required 636 ** to store a copy of an expression or expression tree. They differ in 637 ** how much of the tree is measured. 638 ** 639 ** dupedExprStructSize() Size of only the Expr structure 640 ** dupedExprNodeSize() Size of Expr + space for token 641 ** dupedExprSize() Expr + token + subtree components 642 ** 643 *************************************************************************** 644 ** 645 ** The dupedExprStructSize() function returns two values OR-ed together: 646 ** (1) the space required for a copy of the Expr structure only and 647 ** (2) the EP_xxx flags that indicate what the structure size should be. 648 ** The return values is always one of: 649 ** 650 ** EXPR_FULLSIZE 651 ** EXPR_REDUCEDSIZE | EP_Reduced 652 ** EXPR_TOKENONLYSIZE | EP_TokenOnly 653 ** 654 ** The size of the structure can be found by masking the return value 655 ** of this routine with 0xfff. The flags can be found by masking the 656 ** return value with EP_Reduced|EP_TokenOnly. 657 ** 658 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size 659 ** (unreduced) Expr objects as they or originally constructed by the parser. 660 ** During expression analysis, extra information is computed and moved into 661 ** later parts of teh Expr object and that extra information might get chopped 662 ** off if the expression is reduced. Note also that it does not work to 663 ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal 664 ** to reduce a pristine expression tree from the parser. The implementation 665 ** of dupedExprStructSize() contain multiple assert() statements that attempt 666 ** to enforce this constraint. 667 */ 668 static int dupedExprStructSize(Expr *p, int flags){ 669 int nSize; 670 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ 671 if( 0==(flags&EXPRDUP_REDUCE) ){ 672 nSize = EXPR_FULLSIZE; 673 }else{ 674 assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) ); 675 assert( !ExprHasProperty(p, EP_FromJoin) ); 676 assert( (p->flags2 & EP2_MallocedToken)==0 ); 677 assert( (p->flags2 & EP2_Irreducible)==0 ); 678 if( p->pLeft || p->pRight || p->pColl || p->x.pList ){ 679 nSize = EXPR_REDUCEDSIZE | EP_Reduced; 680 }else{ 681 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; 682 } 683 } 684 return nSize; 685 } 686 687 /* 688 ** This function returns the space in bytes required to store the copy 689 ** of the Expr structure and a copy of the Expr.u.zToken string (if that 690 ** string is defined.) 691 */ 692 static int dupedExprNodeSize(Expr *p, int flags){ 693 int nByte = dupedExprStructSize(p, flags) & 0xfff; 694 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 695 nByte += sqlite3Strlen30(p->u.zToken)+1; 696 } 697 return ROUND8(nByte); 698 } 699 700 /* 701 ** Return the number of bytes required to create a duplicate of the 702 ** expression passed as the first argument. The second argument is a 703 ** mask containing EXPRDUP_XXX flags. 704 ** 705 ** The value returned includes space to create a copy of the Expr struct 706 ** itself and the buffer referred to by Expr.u.zToken, if any. 707 ** 708 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 709 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 710 ** and Expr.pRight variables (but not for any structures pointed to or 711 ** descended from the Expr.x.pList or Expr.x.pSelect variables). 712 */ 713 static int dupedExprSize(Expr *p, int flags){ 714 int nByte = 0; 715 if( p ){ 716 nByte = dupedExprNodeSize(p, flags); 717 if( flags&EXPRDUP_REDUCE ){ 718 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags); 719 } 720 } 721 return nByte; 722 } 723 724 /* 725 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 726 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 727 ** to store the copy of expression p, the copies of p->u.zToken 728 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions, 729 ** if any. Before returning, *pzBuffer is set to the first byte passed the 730 ** portion of the buffer copied into by this function. 731 */ 732 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){ 733 Expr *pNew = 0; /* Value to return */ 734 if( p ){ 735 const int isReduced = (flags&EXPRDUP_REDUCE); 736 u8 *zAlloc; 737 u32 staticFlag = 0; 738 739 assert( pzBuffer==0 || isReduced ); 740 741 /* Figure out where to write the new Expr structure. */ 742 if( pzBuffer ){ 743 zAlloc = *pzBuffer; 744 staticFlag = EP_Static; 745 }else{ 746 zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags)); 747 } 748 pNew = (Expr *)zAlloc; 749 750 if( pNew ){ 751 /* Set nNewSize to the size allocated for the structure pointed to 752 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or 753 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed 754 ** by the copy of the p->u.zToken string (if any). 755 */ 756 const unsigned nStructSize = dupedExprStructSize(p, flags); 757 const int nNewSize = nStructSize & 0xfff; 758 int nToken; 759 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 760 nToken = sqlite3Strlen30(p->u.zToken) + 1; 761 }else{ 762 nToken = 0; 763 } 764 if( isReduced ){ 765 assert( ExprHasProperty(p, EP_Reduced)==0 ); 766 memcpy(zAlloc, p, nNewSize); 767 }else{ 768 int nSize = exprStructSize(p); 769 memcpy(zAlloc, p, nSize); 770 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize); 771 } 772 773 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ 774 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static); 775 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); 776 pNew->flags |= staticFlag; 777 778 /* Copy the p->u.zToken string, if any. */ 779 if( nToken ){ 780 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; 781 memcpy(zToken, p->u.zToken, nToken); 782 } 783 784 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){ 785 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ 786 if( ExprHasProperty(p, EP_xIsSelect) ){ 787 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced); 788 }else{ 789 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced); 790 } 791 } 792 793 /* Fill in pNew->pLeft and pNew->pRight. */ 794 if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){ 795 zAlloc += dupedExprNodeSize(p, flags); 796 if( ExprHasProperty(pNew, EP_Reduced) ){ 797 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc); 798 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc); 799 } 800 if( pzBuffer ){ 801 *pzBuffer = zAlloc; 802 } 803 }else{ 804 pNew->flags2 = 0; 805 if( !ExprHasAnyProperty(p, EP_TokenOnly) ){ 806 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); 807 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); 808 } 809 } 810 811 } 812 } 813 return pNew; 814 } 815 816 /* 817 ** The following group of routines make deep copies of expressions, 818 ** expression lists, ID lists, and select statements. The copies can 819 ** be deleted (by being passed to their respective ...Delete() routines) 820 ** without effecting the originals. 821 ** 822 ** The expression list, ID, and source lists return by sqlite3ExprListDup(), 823 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 824 ** by subsequent calls to sqlite*ListAppend() routines. 825 ** 826 ** Any tables that the SrcList might point to are not duplicated. 827 ** 828 ** The flags parameter contains a combination of the EXPRDUP_XXX flags. 829 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a 830 ** truncated version of the usual Expr structure that will be stored as 831 ** part of the in-memory representation of the database schema. 832 */ 833 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ 834 return exprDup(db, p, flags, 0); 835 } 836 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ 837 ExprList *pNew; 838 struct ExprList_item *pItem, *pOldItem; 839 int i; 840 if( p==0 ) return 0; 841 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) ); 842 if( pNew==0 ) return 0; 843 pNew->iECursor = 0; 844 pNew->nExpr = pNew->nAlloc = p->nExpr; 845 pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) ); 846 if( pItem==0 ){ 847 sqlite3DbFree(db, pNew); 848 return 0; 849 } 850 pOldItem = p->a; 851 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){ 852 Expr *pOldExpr = pOldItem->pExpr; 853 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); 854 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 855 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan); 856 pItem->sortOrder = pOldItem->sortOrder; 857 pItem->done = 0; 858 pItem->iCol = pOldItem->iCol; 859 pItem->iAlias = pOldItem->iAlias; 860 } 861 return pNew; 862 } 863 864 /* 865 ** If cursors, triggers, views and subqueries are all omitted from 866 ** the build, then none of the following routines, except for 867 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes 868 ** called with a NULL argument. 869 */ 870 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ 871 || !defined(SQLITE_OMIT_SUBQUERY) 872 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ 873 SrcList *pNew; 874 int i; 875 int nByte; 876 if( p==0 ) return 0; 877 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); 878 pNew = sqlite3DbMallocRaw(db, nByte ); 879 if( pNew==0 ) return 0; 880 pNew->nSrc = pNew->nAlloc = p->nSrc; 881 for(i=0; i<p->nSrc; i++){ 882 struct SrcList_item *pNewItem = &pNew->a[i]; 883 struct SrcList_item *pOldItem = &p->a[i]; 884 Table *pTab; 885 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); 886 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 887 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); 888 pNewItem->jointype = pOldItem->jointype; 889 pNewItem->iCursor = pOldItem->iCursor; 890 pNewItem->isPopulated = pOldItem->isPopulated; 891 pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex); 892 pNewItem->notIndexed = pOldItem->notIndexed; 893 pNewItem->pIndex = pOldItem->pIndex; 894 pTab = pNewItem->pTab = pOldItem->pTab; 895 if( pTab ){ 896 pTab->nRef++; 897 } 898 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); 899 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); 900 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); 901 pNewItem->colUsed = pOldItem->colUsed; 902 } 903 return pNew; 904 } 905 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ 906 IdList *pNew; 907 int i; 908 if( p==0 ) return 0; 909 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) ); 910 if( pNew==0 ) return 0; 911 pNew->nId = pNew->nAlloc = p->nId; 912 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) ); 913 if( pNew->a==0 ){ 914 sqlite3DbFree(db, pNew); 915 return 0; 916 } 917 for(i=0; i<p->nId; i++){ 918 struct IdList_item *pNewItem = &pNew->a[i]; 919 struct IdList_item *pOldItem = &p->a[i]; 920 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 921 pNewItem->idx = pOldItem->idx; 922 } 923 return pNew; 924 } 925 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ 926 Select *pNew; 927 if( p==0 ) return 0; 928 pNew = sqlite3DbMallocRaw(db, sizeof(*p) ); 929 if( pNew==0 ) return 0; 930 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); 931 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); 932 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); 933 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); 934 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); 935 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); 936 pNew->op = p->op; 937 pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags); 938 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); 939 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags); 940 pNew->iLimit = 0; 941 pNew->iOffset = 0; 942 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; 943 pNew->pRightmost = 0; 944 pNew->addrOpenEphm[0] = -1; 945 pNew->addrOpenEphm[1] = -1; 946 pNew->addrOpenEphm[2] = -1; 947 return pNew; 948 } 949 #else 950 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ 951 assert( p==0 ); 952 return 0; 953 } 954 #endif 955 956 957 /* 958 ** Add a new element to the end of an expression list. If pList is 959 ** initially NULL, then create a new expression list. 960 ** 961 ** If a memory allocation error occurs, the entire list is freed and 962 ** NULL is returned. If non-NULL is returned, then it is guaranteed 963 ** that the new entry was successfully appended. 964 */ 965 ExprList *sqlite3ExprListAppend( 966 Parse *pParse, /* Parsing context */ 967 ExprList *pList, /* List to which to append. Might be NULL */ 968 Expr *pExpr /* Expression to be appended. Might be NULL */ 969 ){ 970 sqlite3 *db = pParse->db; 971 if( pList==0 ){ 972 pList = sqlite3DbMallocZero(db, sizeof(ExprList) ); 973 if( pList==0 ){ 974 goto no_mem; 975 } 976 assert( pList->nAlloc==0 ); 977 } 978 if( pList->nAlloc<=pList->nExpr ){ 979 struct ExprList_item *a; 980 int n = pList->nAlloc*2 + 4; 981 a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0])); 982 if( a==0 ){ 983 goto no_mem; 984 } 985 pList->a = a; 986 pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]); 987 } 988 assert( pList->a!=0 ); 989 if( 1 ){ 990 struct ExprList_item *pItem = &pList->a[pList->nExpr++]; 991 memset(pItem, 0, sizeof(*pItem)); 992 pItem->pExpr = pExpr; 993 } 994 return pList; 995 996 no_mem: 997 /* Avoid leaking memory if malloc has failed. */ 998 sqlite3ExprDelete(db, pExpr); 999 sqlite3ExprListDelete(db, pList); 1000 return 0; 1001 } 1002 1003 /* 1004 ** Set the ExprList.a[].zName element of the most recently added item 1005 ** on the expression list. 1006 ** 1007 ** pList might be NULL following an OOM error. But pName should never be 1008 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 1009 ** is set. 1010 */ 1011 void sqlite3ExprListSetName( 1012 Parse *pParse, /* Parsing context */ 1013 ExprList *pList, /* List to which to add the span. */ 1014 Token *pName, /* Name to be added */ 1015 int dequote /* True to cause the name to be dequoted */ 1016 ){ 1017 assert( pList!=0 || pParse->db->mallocFailed!=0 ); 1018 if( pList ){ 1019 struct ExprList_item *pItem; 1020 assert( pList->nExpr>0 ); 1021 pItem = &pList->a[pList->nExpr-1]; 1022 assert( pItem->zName==0 ); 1023 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); 1024 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName); 1025 } 1026 } 1027 1028 /* 1029 ** Set the ExprList.a[].zSpan element of the most recently added item 1030 ** on the expression list. 1031 ** 1032 ** pList might be NULL following an OOM error. But pSpan should never be 1033 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 1034 ** is set. 1035 */ 1036 void sqlite3ExprListSetSpan( 1037 Parse *pParse, /* Parsing context */ 1038 ExprList *pList, /* List to which to add the span. */ 1039 ExprSpan *pSpan /* The span to be added */ 1040 ){ 1041 sqlite3 *db = pParse->db; 1042 assert( pList!=0 || db->mallocFailed!=0 ); 1043 if( pList ){ 1044 struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; 1045 assert( pList->nExpr>0 ); 1046 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr ); 1047 sqlite3DbFree(db, pItem->zSpan); 1048 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart, 1049 (int)(pSpan->zEnd - pSpan->zStart)); 1050 } 1051 } 1052 1053 /* 1054 ** If the expression list pEList contains more than iLimit elements, 1055 ** leave an error message in pParse. 1056 */ 1057 void sqlite3ExprListCheckLength( 1058 Parse *pParse, 1059 ExprList *pEList, 1060 const char *zObject 1061 ){ 1062 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; 1063 testcase( pEList && pEList->nExpr==mx ); 1064 testcase( pEList && pEList->nExpr==mx+1 ); 1065 if( pEList && pEList->nExpr>mx ){ 1066 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); 1067 } 1068 } 1069 1070 /* 1071 ** Delete an entire expression list. 1072 */ 1073 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ 1074 int i; 1075 struct ExprList_item *pItem; 1076 if( pList==0 ) return; 1077 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) ); 1078 assert( pList->nExpr<=pList->nAlloc ); 1079 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ 1080 sqlite3ExprDelete(db, pItem->pExpr); 1081 sqlite3DbFree(db, pItem->zName); 1082 sqlite3DbFree(db, pItem->zSpan); 1083 } 1084 sqlite3DbFree(db, pList->a); 1085 sqlite3DbFree(db, pList); 1086 } 1087 1088 /* 1089 ** These routines are Walker callbacks. Walker.u.pi is a pointer 1090 ** to an integer. These routines are checking an expression to see 1091 ** if it is a constant. Set *Walker.u.pi to 0 if the expression is 1092 ** not constant. 1093 ** 1094 ** These callback routines are used to implement the following: 1095 ** 1096 ** sqlite3ExprIsConstant() 1097 ** sqlite3ExprIsConstantNotJoin() 1098 ** sqlite3ExprIsConstantOrFunction() 1099 ** 1100 */ 1101 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ 1102 1103 /* If pWalker->u.i is 3 then any term of the expression that comes from 1104 ** the ON or USING clauses of a join disqualifies the expression 1105 ** from being considered constant. */ 1106 if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){ 1107 pWalker->u.i = 0; 1108 return WRC_Abort; 1109 } 1110 1111 switch( pExpr->op ){ 1112 /* Consider functions to be constant if all their arguments are constant 1113 ** and pWalker->u.i==2 */ 1114 case TK_FUNCTION: 1115 if( pWalker->u.i==2 ) return 0; 1116 /* Fall through */ 1117 case TK_ID: 1118 case TK_COLUMN: 1119 case TK_AGG_FUNCTION: 1120 case TK_AGG_COLUMN: 1121 testcase( pExpr->op==TK_ID ); 1122 testcase( pExpr->op==TK_COLUMN ); 1123 testcase( pExpr->op==TK_AGG_FUNCTION ); 1124 testcase( pExpr->op==TK_AGG_COLUMN ); 1125 pWalker->u.i = 0; 1126 return WRC_Abort; 1127 default: 1128 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */ 1129 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */ 1130 return WRC_Continue; 1131 } 1132 } 1133 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){ 1134 UNUSED_PARAMETER(NotUsed); 1135 pWalker->u.i = 0; 1136 return WRC_Abort; 1137 } 1138 static int exprIsConst(Expr *p, int initFlag){ 1139 Walker w; 1140 w.u.i = initFlag; 1141 w.xExprCallback = exprNodeIsConstant; 1142 w.xSelectCallback = selectNodeIsConstant; 1143 sqlite3WalkExpr(&w, p); 1144 return w.u.i; 1145 } 1146 1147 /* 1148 ** Walk an expression tree. Return 1 if the expression is constant 1149 ** and 0 if it involves variables or function calls. 1150 ** 1151 ** For the purposes of this function, a double-quoted string (ex: "abc") 1152 ** is considered a variable but a single-quoted string (ex: 'abc') is 1153 ** a constant. 1154 */ 1155 int sqlite3ExprIsConstant(Expr *p){ 1156 return exprIsConst(p, 1); 1157 } 1158 1159 /* 1160 ** Walk an expression tree. Return 1 if the expression is constant 1161 ** that does no originate from the ON or USING clauses of a join. 1162 ** Return 0 if it involves variables or function calls or terms from 1163 ** an ON or USING clause. 1164 */ 1165 int sqlite3ExprIsConstantNotJoin(Expr *p){ 1166 return exprIsConst(p, 3); 1167 } 1168 1169 /* 1170 ** Walk an expression tree. Return 1 if the expression is constant 1171 ** or a function call with constant arguments. Return and 0 if there 1172 ** are any variables. 1173 ** 1174 ** For the purposes of this function, a double-quoted string (ex: "abc") 1175 ** is considered a variable but a single-quoted string (ex: 'abc') is 1176 ** a constant. 1177 */ 1178 int sqlite3ExprIsConstantOrFunction(Expr *p){ 1179 return exprIsConst(p, 2); 1180 } 1181 1182 /* 1183 ** If the expression p codes a constant integer that is small enough 1184 ** to fit in a 32-bit integer, return 1 and put the value of the integer 1185 ** in *pValue. If the expression is not an integer or if it is too big 1186 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. 1187 */ 1188 int sqlite3ExprIsInteger(Expr *p, int *pValue){ 1189 int rc = 0; 1190 if( p->flags & EP_IntValue ){ 1191 *pValue = p->u.iValue; 1192 return 1; 1193 } 1194 switch( p->op ){ 1195 case TK_INTEGER: { 1196 rc = sqlite3GetInt32(p->u.zToken, pValue); 1197 assert( rc==0 ); 1198 break; 1199 } 1200 case TK_UPLUS: { 1201 rc = sqlite3ExprIsInteger(p->pLeft, pValue); 1202 break; 1203 } 1204 case TK_UMINUS: { 1205 int v; 1206 if( sqlite3ExprIsInteger(p->pLeft, &v) ){ 1207 *pValue = -v; 1208 rc = 1; 1209 } 1210 break; 1211 } 1212 default: break; 1213 } 1214 if( rc ){ 1215 assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly) 1216 || (p->flags2 & EP2_MallocedToken)==0 ); 1217 p->op = TK_INTEGER; 1218 p->flags |= EP_IntValue; 1219 p->u.iValue = *pValue; 1220 } 1221 return rc; 1222 } 1223 1224 /* 1225 ** Return FALSE if there is no chance that the expression can be NULL. 1226 ** 1227 ** If the expression might be NULL or if the expression is too complex 1228 ** to tell return TRUE. 1229 ** 1230 ** This routine is used as an optimization, to skip OP_IsNull opcodes 1231 ** when we know that a value cannot be NULL. Hence, a false positive 1232 ** (returning TRUE when in fact the expression can never be NULL) might 1233 ** be a small performance hit but is otherwise harmless. On the other 1234 ** hand, a false negative (returning FALSE when the result could be NULL) 1235 ** will likely result in an incorrect answer. So when in doubt, return 1236 ** TRUE. 1237 */ 1238 int sqlite3ExprCanBeNull(const Expr *p){ 1239 u8 op; 1240 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } 1241 op = p->op; 1242 if( op==TK_REGISTER ) op = p->op2; 1243 switch( op ){ 1244 case TK_INTEGER: 1245 case TK_STRING: 1246 case TK_FLOAT: 1247 case TK_BLOB: 1248 return 0; 1249 default: 1250 return 1; 1251 } 1252 } 1253 1254 /* 1255 ** Generate an OP_IsNull instruction that tests register iReg and jumps 1256 ** to location iDest if the value in iReg is NULL. The value in iReg 1257 ** was computed by pExpr. If we can look at pExpr at compile-time and 1258 ** determine that it can never generate a NULL, then the OP_IsNull operation 1259 ** can be omitted. 1260 */ 1261 void sqlite3ExprCodeIsNullJump( 1262 Vdbe *v, /* The VDBE under construction */ 1263 const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */ 1264 int iReg, /* Test the value in this register for NULL */ 1265 int iDest /* Jump here if the value is null */ 1266 ){ 1267 if( sqlite3ExprCanBeNull(pExpr) ){ 1268 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest); 1269 } 1270 } 1271 1272 /* 1273 ** Return TRUE if the given expression is a constant which would be 1274 ** unchanged by OP_Affinity with the affinity given in the second 1275 ** argument. 1276 ** 1277 ** This routine is used to determine if the OP_Affinity operation 1278 ** can be omitted. When in doubt return FALSE. A false negative 1279 ** is harmless. A false positive, however, can result in the wrong 1280 ** answer. 1281 */ 1282 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ 1283 u8 op; 1284 if( aff==SQLITE_AFF_NONE ) return 1; 1285 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; } 1286 op = p->op; 1287 if( op==TK_REGISTER ) op = p->op2; 1288 switch( op ){ 1289 case TK_INTEGER: { 1290 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC; 1291 } 1292 case TK_FLOAT: { 1293 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC; 1294 } 1295 case TK_STRING: { 1296 return aff==SQLITE_AFF_TEXT; 1297 } 1298 case TK_BLOB: { 1299 return 1; 1300 } 1301 case TK_COLUMN: { 1302 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ 1303 return p->iColumn<0 1304 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC); 1305 } 1306 default: { 1307 return 0; 1308 } 1309 } 1310 } 1311 1312 /* 1313 ** Return TRUE if the given string is a row-id column name. 1314 */ 1315 int sqlite3IsRowid(const char *z){ 1316 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; 1317 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; 1318 if( sqlite3StrICmp(z, "OID")==0 ) return 1; 1319 return 0; 1320 } 1321 1322 /* 1323 ** Return true if we are able to the IN operator optimization on a 1324 ** query of the form 1325 ** 1326 ** x IN (SELECT ...) 1327 ** 1328 ** Where the SELECT... clause is as specified by the parameter to this 1329 ** routine. 1330 ** 1331 ** The Select object passed in has already been preprocessed and no 1332 ** errors have been found. 1333 */ 1334 #ifndef SQLITE_OMIT_SUBQUERY 1335 static int isCandidateForInOpt(Select *p){ 1336 SrcList *pSrc; 1337 ExprList *pEList; 1338 Table *pTab; 1339 if( p==0 ) return 0; /* right-hand side of IN is SELECT */ 1340 if( p->pPrior ) return 0; /* Not a compound SELECT */ 1341 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ 1342 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 1343 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 1344 return 0; /* No DISTINCT keyword and no aggregate functions */ 1345 } 1346 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ 1347 if( p->pLimit ) return 0; /* Has no LIMIT clause */ 1348 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */ 1349 if( p->pWhere ) return 0; /* Has no WHERE clause */ 1350 pSrc = p->pSrc; 1351 assert( pSrc!=0 ); 1352 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ 1353 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ 1354 pTab = pSrc->a[0].pTab; 1355 if( NEVER(pTab==0) ) return 0; 1356 assert( pTab->pSelect==0 ); /* FROM clause is not a view */ 1357 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ 1358 pEList = p->pEList; 1359 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */ 1360 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */ 1361 return 1; 1362 } 1363 #endif /* SQLITE_OMIT_SUBQUERY */ 1364 1365 /* 1366 ** This function is used by the implementation of the IN (...) operator. 1367 ** It's job is to find or create a b-tree structure that may be used 1368 ** either to test for membership of the (...) set or to iterate through 1369 ** its members, skipping duplicates. 1370 ** 1371 ** The index of the cursor opened on the b-tree (database table, database index 1372 ** or ephermal table) is stored in pX->iTable before this function returns. 1373 ** The returned value of this function indicates the b-tree type, as follows: 1374 ** 1375 ** IN_INDEX_ROWID - The cursor was opened on a database table. 1376 ** IN_INDEX_INDEX - The cursor was opened on a database index. 1377 ** IN_INDEX_EPH - The cursor was opened on a specially created and 1378 ** populated epheremal table. 1379 ** 1380 ** An existing b-tree may only be used if the SELECT is of the simple 1381 ** form: 1382 ** 1383 ** SELECT <column> FROM <table> 1384 ** 1385 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate 1386 ** through the set members, skipping any duplicates. In this case an 1387 ** epheremal table must be used unless the selected <column> is guaranteed 1388 ** to be unique - either because it is an INTEGER PRIMARY KEY or it 1389 ** has a UNIQUE constraint or UNIQUE index. 1390 ** 1391 ** If the prNotFound parameter is not 0, then the b-tree will be used 1392 ** for fast set membership tests. In this case an epheremal table must 1393 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 1394 ** be found with <column> as its left-most column. 1395 ** 1396 ** When the b-tree is being used for membership tests, the calling function 1397 ** needs to know whether or not the structure contains an SQL NULL 1398 ** value in order to correctly evaluate expressions like "X IN (Y, Z)". 1399 ** If there is any chance that the (...) might contain a NULL value at 1400 ** runtime, then a register is allocated and the register number written 1401 ** to *prNotFound. If there is no chance that the (...) contains a 1402 ** NULL value, then *prNotFound is left unchanged. 1403 ** 1404 ** If a register is allocated and its location stored in *prNotFound, then 1405 ** its initial value is NULL. If the (...) does not remain constant 1406 ** for the duration of the query (i.e. the SELECT within the (...) 1407 ** is a correlated subquery) then the value of the allocated register is 1408 ** reset to NULL each time the subquery is rerun. This allows the 1409 ** caller to use vdbe code equivalent to the following: 1410 ** 1411 ** if( register==NULL ){ 1412 ** has_null = <test if data structure contains null> 1413 ** register = 1 1414 ** } 1415 ** 1416 ** in order to avoid running the <test if data structure contains null> 1417 ** test more often than is necessary. 1418 */ 1419 #ifndef SQLITE_OMIT_SUBQUERY 1420 int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ 1421 Select *p; /* SELECT to the right of IN operator */ 1422 int eType = 0; /* Type of RHS table. IN_INDEX_* */ 1423 int iTab = pParse->nTab++; /* Cursor of the RHS table */ 1424 int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */ 1425 1426 assert( pX->op==TK_IN ); 1427 1428 /* Check to see if an existing table or index can be used to 1429 ** satisfy the query. This is preferable to generating a new 1430 ** ephemeral table. 1431 */ 1432 p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0); 1433 if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){ 1434 sqlite3 *db = pParse->db; /* Database connection */ 1435 Expr *pExpr = p->pEList->a[0].pExpr; /* Expression <column> */ 1436 int iCol = pExpr->iColumn; /* Index of column <column> */ 1437 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ 1438 Table *pTab = p->pSrc->a[0].pTab; /* Table <table>. */ 1439 int iDb; /* Database idx for pTab */ 1440 1441 /* Code an OP_VerifyCookie and OP_TableLock for <table>. */ 1442 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1443 sqlite3CodeVerifySchema(pParse, iDb); 1444 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 1445 1446 /* This function is only called from two places. In both cases the vdbe 1447 ** has already been allocated. So assume sqlite3GetVdbe() is always 1448 ** successful here. 1449 */ 1450 assert(v); 1451 if( iCol<0 ){ 1452 int iMem = ++pParse->nMem; 1453 int iAddr; 1454 1455 iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem); 1456 sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem); 1457 1458 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 1459 eType = IN_INDEX_ROWID; 1460 1461 sqlite3VdbeJumpHere(v, iAddr); 1462 }else{ 1463 Index *pIdx; /* Iterator variable */ 1464 1465 /* The collation sequence used by the comparison. If an index is to 1466 ** be used in place of a temp-table, it must be ordered according 1467 ** to this collation sequence. */ 1468 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr); 1469 1470 /* Check that the affinity that will be used to perform the 1471 ** comparison is the same as the affinity of the column. If 1472 ** it is not, it is not possible to use any index. 1473 */ 1474 char aff = comparisonAffinity(pX); 1475 int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE); 1476 1477 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){ 1478 if( (pIdx->aiColumn[0]==iCol) 1479 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq 1480 && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None)) 1481 ){ 1482 int iMem = ++pParse->nMem; 1483 int iAddr; 1484 char *pKey; 1485 1486 pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx); 1487 iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem); 1488 sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem); 1489 1490 sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb, 1491 pKey,P4_KEYINFO_HANDOFF); 1492 VdbeComment((v, "%s", pIdx->zName)); 1493 eType = IN_INDEX_INDEX; 1494 1495 sqlite3VdbeJumpHere(v, iAddr); 1496 if( prNotFound && !pTab->aCol[iCol].notNull ){ 1497 *prNotFound = ++pParse->nMem; 1498 } 1499 } 1500 } 1501 } 1502 } 1503 1504 if( eType==0 ){ 1505 /* Could not found an existing table or index to use as the RHS b-tree. 1506 ** We will have to generate an ephemeral table to do the job. 1507 */ 1508 int rMayHaveNull = 0; 1509 eType = IN_INDEX_EPH; 1510 if( prNotFound ){ 1511 *prNotFound = rMayHaveNull = ++pParse->nMem; 1512 }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){ 1513 eType = IN_INDEX_ROWID; 1514 } 1515 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID); 1516 }else{ 1517 pX->iTable = iTab; 1518 } 1519 return eType; 1520 } 1521 #endif 1522 1523 /* 1524 ** Generate code for scalar subqueries used as an expression 1525 ** and IN operators. Examples: 1526 ** 1527 ** (SELECT a FROM b) -- subquery 1528 ** EXISTS (SELECT a FROM b) -- EXISTS subquery 1529 ** x IN (4,5,11) -- IN operator with list on right-hand side 1530 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right 1531 ** 1532 ** The pExpr parameter describes the expression that contains the IN 1533 ** operator or subquery. 1534 ** 1535 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed 1536 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference 1537 ** to some integer key column of a table B-Tree. In this case, use an 1538 ** intkey B-Tree to store the set of IN(...) values instead of the usual 1539 ** (slower) variable length keys B-Tree. 1540 ** 1541 ** If rMayHaveNull is non-zero, that means that the operation is an IN 1542 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs. 1543 ** Furthermore, the IN is in a WHERE clause and that we really want 1544 ** to iterate over the RHS of the IN operator in order to quickly locate 1545 ** all corresponding LHS elements. All this routine does is initialize 1546 ** the register given by rMayHaveNull to NULL. Calling routines will take 1547 ** care of changing this register value to non-NULL if the RHS is NULL-free. 1548 ** 1549 ** If rMayHaveNull is zero, that means that the subquery is being used 1550 ** for membership testing only. There is no need to initialize any 1551 ** registers to indicate the presense or absence of NULLs on the RHS. 1552 ** 1553 ** For a SELECT or EXISTS operator, return the register that holds the 1554 ** result. For IN operators or if an error occurs, the return value is 0. 1555 */ 1556 #ifndef SQLITE_OMIT_SUBQUERY 1557 int sqlite3CodeSubselect( 1558 Parse *pParse, /* Parsing context */ 1559 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */ 1560 int rMayHaveNull, /* Register that records whether NULLs exist in RHS */ 1561 int isRowid /* If true, LHS of IN operator is a rowid */ 1562 ){ 1563 int testAddr = 0; /* One-time test address */ 1564 int rReg = 0; /* Register storing resulting */ 1565 Vdbe *v = sqlite3GetVdbe(pParse); 1566 if( NEVER(v==0) ) return 0; 1567 sqlite3ExprCachePush(pParse); 1568 1569 /* This code must be run in its entirety every time it is encountered 1570 ** if any of the following is true: 1571 ** 1572 ** * The right-hand side is a correlated subquery 1573 ** * The right-hand side is an expression list containing variables 1574 ** * We are inside a trigger 1575 ** 1576 ** If all of the above are false, then we can run this code just once 1577 ** save the results, and reuse the same result on subsequent invocations. 1578 */ 1579 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){ 1580 int mem = ++pParse->nMem; 1581 sqlite3VdbeAddOp1(v, OP_If, mem); 1582 testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem); 1583 assert( testAddr>0 || pParse->db->mallocFailed ); 1584 } 1585 1586 switch( pExpr->op ){ 1587 case TK_IN: { 1588 char affinity; 1589 KeyInfo keyInfo; 1590 int addr; /* Address of OP_OpenEphemeral instruction */ 1591 Expr *pLeft = pExpr->pLeft; 1592 1593 if( rMayHaveNull ){ 1594 sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull); 1595 } 1596 1597 affinity = sqlite3ExprAffinity(pLeft); 1598 1599 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)' 1600 ** expression it is handled the same way. An ephemeral table is 1601 ** filled with single-field index keys representing the results 1602 ** from the SELECT or the <exprlist>. 1603 ** 1604 ** If the 'x' expression is a column value, or the SELECT... 1605 ** statement returns a column value, then the affinity of that 1606 ** column is used to build the index keys. If both 'x' and the 1607 ** SELECT... statement are columns, then numeric affinity is used 1608 ** if either column has NUMERIC or INTEGER affinity. If neither 1609 ** 'x' nor the SELECT... statement are columns, then numeric affinity 1610 ** is used. 1611 */ 1612 pExpr->iTable = pParse->nTab++; 1613 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid); 1614 memset(&keyInfo, 0, sizeof(keyInfo)); 1615 keyInfo.nField = 1; 1616 1617 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 1618 /* Case 1: expr IN (SELECT ...) 1619 ** 1620 ** Generate code to write the results of the select into the temporary 1621 ** table allocated and opened above. 1622 */ 1623 SelectDest dest; 1624 ExprList *pEList; 1625 1626 assert( !isRowid ); 1627 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable); 1628 dest.affinity = (u8)affinity; 1629 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); 1630 if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){ 1631 return 0; 1632 } 1633 pEList = pExpr->x.pSelect->pEList; 1634 if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 1635 keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, 1636 pEList->a[0].pExpr); 1637 } 1638 }else if( pExpr->x.pList!=0 ){ 1639 /* Case 2: expr IN (exprlist) 1640 ** 1641 ** For each expression, build an index key from the evaluation and 1642 ** store it in the temporary table. If <expr> is a column, then use 1643 ** that columns affinity when building index keys. If <expr> is not 1644 ** a column, use numeric affinity. 1645 */ 1646 int i; 1647 ExprList *pList = pExpr->x.pList; 1648 struct ExprList_item *pItem; 1649 int r1, r2, r3; 1650 1651 if( !affinity ){ 1652 affinity = SQLITE_AFF_NONE; 1653 } 1654 keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 1655 1656 /* Loop through each expression in <exprlist>. */ 1657 r1 = sqlite3GetTempReg(pParse); 1658 r2 = sqlite3GetTempReg(pParse); 1659 sqlite3VdbeAddOp2(v, OP_Null, 0, r2); 1660 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ 1661 Expr *pE2 = pItem->pExpr; 1662 int iValToIns; 1663 1664 /* If the expression is not constant then we will need to 1665 ** disable the test that was generated above that makes sure 1666 ** this code only executes once. Because for a non-constant 1667 ** expression we need to rerun this code each time. 1668 */ 1669 if( testAddr && !sqlite3ExprIsConstant(pE2) ){ 1670 sqlite3VdbeChangeToNoop(v, testAddr-1, 2); 1671 testAddr = 0; 1672 } 1673 1674 /* Evaluate the expression and insert it into the temp table */ 1675 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){ 1676 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns); 1677 }else{ 1678 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); 1679 if( isRowid ){ 1680 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3, 1681 sqlite3VdbeCurrentAddr(v)+2); 1682 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3); 1683 }else{ 1684 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); 1685 sqlite3ExprCacheAffinityChange(pParse, r3, 1); 1686 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2); 1687 } 1688 } 1689 } 1690 sqlite3ReleaseTempReg(pParse, r1); 1691 sqlite3ReleaseTempReg(pParse, r2); 1692 } 1693 if( !isRowid ){ 1694 sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO); 1695 } 1696 break; 1697 } 1698 1699 case TK_EXISTS: 1700 case TK_SELECT: 1701 default: { 1702 /* If this has to be a scalar SELECT. Generate code to put the 1703 ** value of this select in a memory cell and record the number 1704 ** of the memory cell in iColumn. If this is an EXISTS, write 1705 ** an integer 0 (not exists) or 1 (exists) into a memory cell 1706 ** and record that memory cell in iColumn. 1707 */ 1708 static const Token one = { "1", 1 }; /* Token for literal value 1 */ 1709 Select *pSel; /* SELECT statement to encode */ 1710 SelectDest dest; /* How to deal with SELECt result */ 1711 1712 testcase( pExpr->op==TK_EXISTS ); 1713 testcase( pExpr->op==TK_SELECT ); 1714 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); 1715 1716 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 1717 pSel = pExpr->x.pSelect; 1718 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem); 1719 if( pExpr->op==TK_SELECT ){ 1720 dest.eDest = SRT_Mem; 1721 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm); 1722 VdbeComment((v, "Init subquery result")); 1723 }else{ 1724 dest.eDest = SRT_Exists; 1725 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm); 1726 VdbeComment((v, "Init EXISTS result")); 1727 } 1728 sqlite3ExprDelete(pParse->db, pSel->pLimit); 1729 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one); 1730 if( sqlite3Select(pParse, pSel, &dest) ){ 1731 return 0; 1732 } 1733 rReg = dest.iParm; 1734 ExprSetIrreducible(pExpr); 1735 break; 1736 } 1737 } 1738 1739 if( testAddr ){ 1740 sqlite3VdbeJumpHere(v, testAddr-1); 1741 } 1742 sqlite3ExprCachePop(pParse, 1); 1743 1744 return rReg; 1745 } 1746 #endif /* SQLITE_OMIT_SUBQUERY */ 1747 1748 #ifndef SQLITE_OMIT_SUBQUERY 1749 /* 1750 ** Generate code for an IN expression. 1751 ** 1752 ** x IN (SELECT ...) 1753 ** x IN (value, value, ...) 1754 ** 1755 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS) 1756 ** is an array of zero or more values. The expression is true if the LHS is 1757 ** contained within the RHS. The value of the expression is unknown (NULL) 1758 ** if the LHS is NULL or if the LHS is not contained within the RHS and the 1759 ** RHS contains one or more NULL values. 1760 ** 1761 ** This routine generates code will jump to destIfFalse if the LHS is not 1762 ** contained within the RHS. If due to NULLs we cannot determine if the LHS 1763 ** is contained in the RHS then jump to destIfNull. If the LHS is contained 1764 ** within the RHS then fall through. 1765 */ 1766 static void sqlite3ExprCodeIN( 1767 Parse *pParse, /* Parsing and code generating context */ 1768 Expr *pExpr, /* The IN expression */ 1769 int destIfFalse, /* Jump here if LHS is not contained in the RHS */ 1770 int destIfNull /* Jump here if the results are unknown due to NULLs */ 1771 ){ 1772 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ 1773 char affinity; /* Comparison affinity to use */ 1774 int eType; /* Type of the RHS */ 1775 int r1; /* Temporary use register */ 1776 Vdbe *v; /* Statement under construction */ 1777 1778 /* Compute the RHS. After this step, the table with cursor 1779 ** pExpr->iTable will contains the values that make up the RHS. 1780 */ 1781 v = pParse->pVdbe; 1782 assert( v!=0 ); /* OOM detected prior to this routine */ 1783 VdbeNoopComment((v, "begin IN expr")); 1784 eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull); 1785 1786 /* Figure out the affinity to use to create a key from the results 1787 ** of the expression. affinityStr stores a static string suitable for 1788 ** P4 of OP_MakeRecord. 1789 */ 1790 affinity = comparisonAffinity(pExpr); 1791 1792 /* Code the LHS, the <expr> from "<expr> IN (...)". 1793 */ 1794 sqlite3ExprCachePush(pParse); 1795 r1 = sqlite3GetTempReg(pParse); 1796 sqlite3ExprCode(pParse, pExpr->pLeft, r1); 1797 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); 1798 1799 1800 if( eType==IN_INDEX_ROWID ){ 1801 /* In this case, the RHS is the ROWID of table b-tree 1802 */ 1803 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); 1804 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1); 1805 }else{ 1806 /* In this case, the RHS is an index b-tree. 1807 */ 1808 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1); 1809 1810 /* If the set membership test fails, then the result of the 1811 ** "x IN (...)" expression must be either 0 or NULL. If the set 1812 ** contains no NULL values, then the result is 0. If the set 1813 ** contains one or more NULL values, then the result of the 1814 ** expression is also NULL. 1815 */ 1816 if( rRhsHasNull==0 || destIfFalse==destIfNull ){ 1817 /* This branch runs if it is known at compile time that the RHS 1818 ** cannot contain NULL values. This happens as the result 1819 ** of a "NOT NULL" constraint in the database schema. 1820 ** 1821 ** Also run this branch if NULL is equivalent to FALSE 1822 ** for this particular IN operator. 1823 */ 1824 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1); 1825 1826 }else{ 1827 /* In this branch, the RHS of the IN might contain a NULL and 1828 ** the presence of a NULL on the RHS makes a difference in the 1829 ** outcome. 1830 */ 1831 int j1, j2, j3; 1832 1833 /* First check to see if the LHS is contained in the RHS. If so, 1834 ** then the presence of NULLs in the RHS does not matter, so jump 1835 ** over all of the code that follows. 1836 */ 1837 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1); 1838 1839 /* Here we begin generating code that runs if the LHS is not 1840 ** contained within the RHS. Generate additional code that 1841 ** tests the RHS for NULLs. If the RHS contains a NULL then 1842 ** jump to destIfNull. If there are no NULLs in the RHS then 1843 ** jump to destIfFalse. 1844 */ 1845 j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull); 1846 j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1); 1847 sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull); 1848 sqlite3VdbeJumpHere(v, j3); 1849 sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1); 1850 sqlite3VdbeJumpHere(v, j2); 1851 1852 /* Jump to the appropriate target depending on whether or not 1853 ** the RHS contains a NULL 1854 */ 1855 sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull); 1856 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); 1857 1858 /* The OP_Found at the top of this branch jumps here when true, 1859 ** causing the overall IN expression evaluation to fall through. 1860 */ 1861 sqlite3VdbeJumpHere(v, j1); 1862 } 1863 } 1864 sqlite3ReleaseTempReg(pParse, r1); 1865 sqlite3ExprCachePop(pParse, 1); 1866 VdbeComment((v, "end IN expr")); 1867 } 1868 #endif /* SQLITE_OMIT_SUBQUERY */ 1869 1870 /* 1871 ** Duplicate an 8-byte value 1872 */ 1873 static char *dup8bytes(Vdbe *v, const char *in){ 1874 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8); 1875 if( out ){ 1876 memcpy(out, in, 8); 1877 } 1878 return out; 1879 } 1880 1881 #ifndef SQLITE_OMIT_FLOATING_POINT 1882 /* 1883 ** Generate an instruction that will put the floating point 1884 ** value described by z[0..n-1] into register iMem. 1885 ** 1886 ** The z[] string will probably not be zero-terminated. But the 1887 ** z[n] character is guaranteed to be something that does not look 1888 ** like the continuation of the number. 1889 */ 1890 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ 1891 if( ALWAYS(z!=0) ){ 1892 double value; 1893 char *zV; 1894 sqlite3AtoF(z, &value); 1895 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ 1896 if( negateFlag ) value = -value; 1897 zV = dup8bytes(v, (char*)&value); 1898 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL); 1899 } 1900 } 1901 #endif 1902 1903 1904 /* 1905 ** Generate an instruction that will put the integer describe by 1906 ** text z[0..n-1] into register iMem. 1907 ** 1908 ** The z[] string will probably not be zero-terminated. But the 1909 ** z[n] character is guaranteed to be something that does not look 1910 ** like the continuation of the number. 1911 */ 1912 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ 1913 Vdbe *v = pParse->pVdbe; 1914 if( pExpr->flags & EP_IntValue ){ 1915 int i = pExpr->u.iValue; 1916 if( negFlag ) i = -i; 1917 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); 1918 }else{ 1919 const char *z = pExpr->u.zToken; 1920 assert( z!=0 ); 1921 if( sqlite3FitsIn64Bits(z, negFlag) ){ 1922 i64 value; 1923 char *zV; 1924 sqlite3Atoi64(z, &value); 1925 if( negFlag ) value = -value; 1926 zV = dup8bytes(v, (char*)&value); 1927 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64); 1928 }else{ 1929 #ifdef SQLITE_OMIT_FLOATING_POINT 1930 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); 1931 #else 1932 codeReal(v, z, negFlag, iMem); 1933 #endif 1934 } 1935 } 1936 } 1937 1938 /* 1939 ** Clear a cache entry. 1940 */ 1941 static void cacheEntryClear(Parse *pParse, struct yColCache *p){ 1942 if( p->tempReg ){ 1943 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){ 1944 pParse->aTempReg[pParse->nTempReg++] = p->iReg; 1945 } 1946 p->tempReg = 0; 1947 } 1948 } 1949 1950 1951 /* 1952 ** Record in the column cache that a particular column from a 1953 ** particular table is stored in a particular register. 1954 */ 1955 void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){ 1956 int i; 1957 int minLru; 1958 int idxLru; 1959 struct yColCache *p; 1960 1961 assert( iReg>0 ); /* Register numbers are always positive */ 1962 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */ 1963 1964 /* The SQLITE_ColumnCache flag disables the column cache. This is used 1965 ** for testing only - to verify that SQLite always gets the same answer 1966 ** with and without the column cache. 1967 */ 1968 if( pParse->db->flags & SQLITE_ColumnCache ) return; 1969 1970 /* First replace any existing entry. 1971 ** 1972 ** Actually, the way the column cache is currently used, we are guaranteed 1973 ** that the object will never already be in cache. Verify this guarantee. 1974 */ 1975 #ifndef NDEBUG 1976 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 1977 #if 0 /* This code wold remove the entry from the cache if it existed */ 1978 if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){ 1979 cacheEntryClear(pParse, p); 1980 p->iLevel = pParse->iCacheLevel; 1981 p->iReg = iReg; 1982 p->lru = pParse->iCacheCnt++; 1983 return; 1984 } 1985 #endif 1986 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol ); 1987 } 1988 #endif 1989 1990 /* Find an empty slot and replace it */ 1991 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 1992 if( p->iReg==0 ){ 1993 p->iLevel = pParse->iCacheLevel; 1994 p->iTable = iTab; 1995 p->iColumn = iCol; 1996 p->iReg = iReg; 1997 p->tempReg = 0; 1998 p->lru = pParse->iCacheCnt++; 1999 return; 2000 } 2001 } 2002 2003 /* Replace the last recently used */ 2004 minLru = 0x7fffffff; 2005 idxLru = -1; 2006 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 2007 if( p->lru<minLru ){ 2008 idxLru = i; 2009 minLru = p->lru; 2010 } 2011 } 2012 if( ALWAYS(idxLru>=0) ){ 2013 p = &pParse->aColCache[idxLru]; 2014 p->iLevel = pParse->iCacheLevel; 2015 p->iTable = iTab; 2016 p->iColumn = iCol; 2017 p->iReg = iReg; 2018 p->tempReg = 0; 2019 p->lru = pParse->iCacheCnt++; 2020 return; 2021 } 2022 } 2023 2024 /* 2025 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten. 2026 ** Purge the range of registers from the column cache. 2027 */ 2028 void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){ 2029 int i; 2030 int iLast = iReg + nReg - 1; 2031 struct yColCache *p; 2032 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 2033 int r = p->iReg; 2034 if( r>=iReg && r<=iLast ){ 2035 cacheEntryClear(pParse, p); 2036 p->iReg = 0; 2037 } 2038 } 2039 } 2040 2041 /* 2042 ** Remember the current column cache context. Any new entries added 2043 ** added to the column cache after this call are removed when the 2044 ** corresponding pop occurs. 2045 */ 2046 void sqlite3ExprCachePush(Parse *pParse){ 2047 pParse->iCacheLevel++; 2048 } 2049 2050 /* 2051 ** Remove from the column cache any entries that were added since the 2052 ** the previous N Push operations. In other words, restore the cache 2053 ** to the state it was in N Pushes ago. 2054 */ 2055 void sqlite3ExprCachePop(Parse *pParse, int N){ 2056 int i; 2057 struct yColCache *p; 2058 assert( N>0 ); 2059 assert( pParse->iCacheLevel>=N ); 2060 pParse->iCacheLevel -= N; 2061 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 2062 if( p->iReg && p->iLevel>pParse->iCacheLevel ){ 2063 cacheEntryClear(pParse, p); 2064 p->iReg = 0; 2065 } 2066 } 2067 } 2068 2069 /* 2070 ** When a cached column is reused, make sure that its register is 2071 ** no longer available as a temp register. ticket #3879: that same 2072 ** register might be in the cache in multiple places, so be sure to 2073 ** get them all. 2074 */ 2075 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){ 2076 int i; 2077 struct yColCache *p; 2078 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 2079 if( p->iReg==iReg ){ 2080 p->tempReg = 0; 2081 } 2082 } 2083 } 2084 2085 /* 2086 ** Generate code to extract the value of the iCol-th column of a table. 2087 */ 2088 void sqlite3ExprCodeGetColumnOfTable( 2089 Vdbe *v, /* The VDBE under construction */ 2090 Table *pTab, /* The table containing the value */ 2091 int iTabCur, /* The cursor for this table */ 2092 int iCol, /* Index of the column to extract */ 2093 int regOut /* Extract the valud into this register */ 2094 ){ 2095 if( iCol<0 || iCol==pTab->iPKey ){ 2096 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); 2097 }else{ 2098 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; 2099 sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut); 2100 } 2101 if( iCol>=0 ){ 2102 sqlite3ColumnDefault(v, pTab, iCol, regOut); 2103 } 2104 } 2105 2106 /* 2107 ** Generate code that will extract the iColumn-th column from 2108 ** table pTab and store the column value in a register. An effort 2109 ** is made to store the column value in register iReg, but this is 2110 ** not guaranteed. The location of the column value is returned. 2111 ** 2112 ** There must be an open cursor to pTab in iTable when this routine 2113 ** is called. If iColumn<0 then code is generated that extracts the rowid. 2114 */ 2115 int sqlite3ExprCodeGetColumn( 2116 Parse *pParse, /* Parsing and code generating context */ 2117 Table *pTab, /* Description of the table we are reading from */ 2118 int iColumn, /* Index of the table column */ 2119 int iTable, /* The cursor pointing to the table */ 2120 int iReg /* Store results here */ 2121 ){ 2122 Vdbe *v = pParse->pVdbe; 2123 int i; 2124 struct yColCache *p; 2125 2126 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 2127 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){ 2128 p->lru = pParse->iCacheCnt++; 2129 sqlite3ExprCachePinRegister(pParse, p->iReg); 2130 return p->iReg; 2131 } 2132 } 2133 assert( v!=0 ); 2134 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg); 2135 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg); 2136 return iReg; 2137 } 2138 2139 /* 2140 ** Clear all column cache entries. 2141 */ 2142 void sqlite3ExprCacheClear(Parse *pParse){ 2143 int i; 2144 struct yColCache *p; 2145 2146 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 2147 if( p->iReg ){ 2148 cacheEntryClear(pParse, p); 2149 p->iReg = 0; 2150 } 2151 } 2152 } 2153 2154 /* 2155 ** Record the fact that an affinity change has occurred on iCount 2156 ** registers starting with iStart. 2157 */ 2158 void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){ 2159 sqlite3ExprCacheRemove(pParse, iStart, iCount); 2160 } 2161 2162 /* 2163 ** Generate code to move content from registers iFrom...iFrom+nReg-1 2164 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. 2165 */ 2166 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ 2167 int i; 2168 struct yColCache *p; 2169 if( NEVER(iFrom==iTo) ) return; 2170 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); 2171 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 2172 int x = p->iReg; 2173 if( x>=iFrom && x<iFrom+nReg ){ 2174 p->iReg += iTo-iFrom; 2175 } 2176 } 2177 } 2178 2179 /* 2180 ** Generate code to copy content from registers iFrom...iFrom+nReg-1 2181 ** over to iTo..iTo+nReg-1. 2182 */ 2183 void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){ 2184 int i; 2185 if( NEVER(iFrom==iTo) ) return; 2186 for(i=0; i<nReg; i++){ 2187 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i); 2188 } 2189 } 2190 2191 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST) 2192 /* 2193 ** Return true if any register in the range iFrom..iTo (inclusive) 2194 ** is used as part of the column cache. 2195 ** 2196 ** This routine is used within assert() and testcase() macros only 2197 ** and does not appear in a normal build. 2198 */ 2199 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){ 2200 int i; 2201 struct yColCache *p; 2202 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 2203 int r = p->iReg; 2204 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/ 2205 } 2206 return 0; 2207 } 2208 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */ 2209 2210 /* 2211 ** If the last instruction coded is an ephemeral copy of any of 2212 ** the registers in the nReg registers beginning with iReg, then 2213 ** convert the last instruction from OP_SCopy to OP_Copy. 2214 */ 2215 void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){ 2216 VdbeOp *pOp; 2217 Vdbe *v; 2218 2219 assert( pParse->db->mallocFailed==0 ); 2220 v = pParse->pVdbe; 2221 assert( v!=0 ); 2222 pOp = sqlite3VdbeGetOp(v, -1); 2223 assert( pOp!=0 ); 2224 if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){ 2225 pOp->opcode = OP_Copy; 2226 } 2227 } 2228 2229 /* 2230 ** Generate code to store the value of the iAlias-th alias in register 2231 ** target. The first time this is called, pExpr is evaluated to compute 2232 ** the value of the alias. The value is stored in an auxiliary register 2233 ** and the number of that register is returned. On subsequent calls, 2234 ** the register number is returned without generating any code. 2235 ** 2236 ** Note that in order for this to work, code must be generated in the 2237 ** same order that it is executed. 2238 ** 2239 ** Aliases are numbered starting with 1. So iAlias is in the range 2240 ** of 1 to pParse->nAlias inclusive. 2241 ** 2242 ** pParse->aAlias[iAlias-1] records the register number where the value 2243 ** of the iAlias-th alias is stored. If zero, that means that the 2244 ** alias has not yet been computed. 2245 */ 2246 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){ 2247 #if 0 2248 sqlite3 *db = pParse->db; 2249 int iReg; 2250 if( pParse->nAliasAlloc<pParse->nAlias ){ 2251 pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias, 2252 sizeof(pParse->aAlias[0])*pParse->nAlias ); 2253 testcase( db->mallocFailed && pParse->nAliasAlloc>0 ); 2254 if( db->mallocFailed ) return 0; 2255 memset(&pParse->aAlias[pParse->nAliasAlloc], 0, 2256 (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0])); 2257 pParse->nAliasAlloc = pParse->nAlias; 2258 } 2259 assert( iAlias>0 && iAlias<=pParse->nAlias ); 2260 iReg = pParse->aAlias[iAlias-1]; 2261 if( iReg==0 ){ 2262 if( pParse->iCacheLevel>0 ){ 2263 iReg = sqlite3ExprCodeTarget(pParse, pExpr, target); 2264 }else{ 2265 iReg = ++pParse->nMem; 2266 sqlite3ExprCode(pParse, pExpr, iReg); 2267 pParse->aAlias[iAlias-1] = iReg; 2268 } 2269 } 2270 return iReg; 2271 #else 2272 UNUSED_PARAMETER(iAlias); 2273 return sqlite3ExprCodeTarget(pParse, pExpr, target); 2274 #endif 2275 } 2276 2277 /* 2278 ** Generate code into the current Vdbe to evaluate the given 2279 ** expression. Attempt to store the results in register "target". 2280 ** Return the register where results are stored. 2281 ** 2282 ** With this routine, there is no guarantee that results will 2283 ** be stored in target. The result might be stored in some other 2284 ** register if it is convenient to do so. The calling function 2285 ** must check the return code and move the results to the desired 2286 ** register. 2287 */ 2288 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ 2289 Vdbe *v = pParse->pVdbe; /* The VM under construction */ 2290 int op; /* The opcode being coded */ 2291 int inReg = target; /* Results stored in register inReg */ 2292 int regFree1 = 0; /* If non-zero free this temporary register */ 2293 int regFree2 = 0; /* If non-zero free this temporary register */ 2294 int r1, r2, r3, r4; /* Various register numbers */ 2295 sqlite3 *db = pParse->db; /* The database connection */ 2296 2297 assert( target>0 && target<=pParse->nMem ); 2298 if( v==0 ){ 2299 assert( pParse->db->mallocFailed ); 2300 return 0; 2301 } 2302 2303 if( pExpr==0 ){ 2304 op = TK_NULL; 2305 }else{ 2306 op = pExpr->op; 2307 } 2308 switch( op ){ 2309 case TK_AGG_COLUMN: { 2310 AggInfo *pAggInfo = pExpr->pAggInfo; 2311 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; 2312 if( !pAggInfo->directMode ){ 2313 assert( pCol->iMem>0 ); 2314 inReg = pCol->iMem; 2315 break; 2316 }else if( pAggInfo->useSortingIdx ){ 2317 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx, 2318 pCol->iSorterColumn, target); 2319 break; 2320 } 2321 /* Otherwise, fall thru into the TK_COLUMN case */ 2322 } 2323 case TK_COLUMN: { 2324 if( pExpr->iTable<0 ){ 2325 /* This only happens when coding check constraints */ 2326 assert( pParse->ckBase>0 ); 2327 inReg = pExpr->iColumn + pParse->ckBase; 2328 }else{ 2329 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab, 2330 pExpr->iColumn, pExpr->iTable, target); 2331 } 2332 break; 2333 } 2334 case TK_INTEGER: { 2335 codeInteger(pParse, pExpr, 0, target); 2336 break; 2337 } 2338 #ifndef SQLITE_OMIT_FLOATING_POINT 2339 case TK_FLOAT: { 2340 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2341 codeReal(v, pExpr->u.zToken, 0, target); 2342 break; 2343 } 2344 #endif 2345 case TK_STRING: { 2346 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2347 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0); 2348 break; 2349 } 2350 case TK_NULL: { 2351 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 2352 break; 2353 } 2354 #ifndef SQLITE_OMIT_BLOB_LITERAL 2355 case TK_BLOB: { 2356 int n; 2357 const char *z; 2358 char *zBlob; 2359 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2360 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); 2361 assert( pExpr->u.zToken[1]=='\'' ); 2362 z = &pExpr->u.zToken[2]; 2363 n = sqlite3Strlen30(z) - 1; 2364 assert( z[n]=='\'' ); 2365 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); 2366 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); 2367 break; 2368 } 2369 #endif 2370 case TK_VARIABLE: { 2371 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2372 assert( pExpr->u.zToken!=0 ); 2373 assert( pExpr->u.zToken[0]!=0 ); 2374 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); 2375 if( pExpr->u.zToken[1]!=0 ){ 2376 sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0); 2377 } 2378 break; 2379 } 2380 case TK_REGISTER: { 2381 inReg = pExpr->iTable; 2382 break; 2383 } 2384 case TK_AS: { 2385 inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target); 2386 break; 2387 } 2388 #ifndef SQLITE_OMIT_CAST 2389 case TK_CAST: { 2390 /* Expressions of the form: CAST(pLeft AS token) */ 2391 int aff, to_op; 2392 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); 2393 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2394 aff = sqlite3AffinityType(pExpr->u.zToken); 2395 to_op = aff - SQLITE_AFF_TEXT + OP_ToText; 2396 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT ); 2397 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE ); 2398 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC ); 2399 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER ); 2400 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL ); 2401 testcase( to_op==OP_ToText ); 2402 testcase( to_op==OP_ToBlob ); 2403 testcase( to_op==OP_ToNumeric ); 2404 testcase( to_op==OP_ToInt ); 2405 testcase( to_op==OP_ToReal ); 2406 if( inReg!=target ){ 2407 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); 2408 inReg = target; 2409 } 2410 sqlite3VdbeAddOp1(v, to_op, inReg); 2411 testcase( usedAsColumnCache(pParse, inReg, inReg) ); 2412 sqlite3ExprCacheAffinityChange(pParse, inReg, 1); 2413 break; 2414 } 2415 #endif /* SQLITE_OMIT_CAST */ 2416 case TK_LT: 2417 case TK_LE: 2418 case TK_GT: 2419 case TK_GE: 2420 case TK_NE: 2421 case TK_EQ: { 2422 assert( TK_LT==OP_Lt ); 2423 assert( TK_LE==OP_Le ); 2424 assert( TK_GT==OP_Gt ); 2425 assert( TK_GE==OP_Ge ); 2426 assert( TK_EQ==OP_Eq ); 2427 assert( TK_NE==OP_Ne ); 2428 testcase( op==TK_LT ); 2429 testcase( op==TK_LE ); 2430 testcase( op==TK_GT ); 2431 testcase( op==TK_GE ); 2432 testcase( op==TK_EQ ); 2433 testcase( op==TK_NE ); 2434 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 2435 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 2436 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 2437 r1, r2, inReg, SQLITE_STOREP2); 2438 testcase( regFree1==0 ); 2439 testcase( regFree2==0 ); 2440 break; 2441 } 2442 case TK_IS: 2443 case TK_ISNOT: { 2444 testcase( op==TK_IS ); 2445 testcase( op==TK_ISNOT ); 2446 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 2447 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 2448 op = (op==TK_IS) ? TK_EQ : TK_NE; 2449 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 2450 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ); 2451 testcase( regFree1==0 ); 2452 testcase( regFree2==0 ); 2453 break; 2454 } 2455 case TK_AND: 2456 case TK_OR: 2457 case TK_PLUS: 2458 case TK_STAR: 2459 case TK_MINUS: 2460 case TK_REM: 2461 case TK_BITAND: 2462 case TK_BITOR: 2463 case TK_SLASH: 2464 case TK_LSHIFT: 2465 case TK_RSHIFT: 2466 case TK_CONCAT: { 2467 assert( TK_AND==OP_And ); 2468 assert( TK_OR==OP_Or ); 2469 assert( TK_PLUS==OP_Add ); 2470 assert( TK_MINUS==OP_Subtract ); 2471 assert( TK_REM==OP_Remainder ); 2472 assert( TK_BITAND==OP_BitAnd ); 2473 assert( TK_BITOR==OP_BitOr ); 2474 assert( TK_SLASH==OP_Divide ); 2475 assert( TK_LSHIFT==OP_ShiftLeft ); 2476 assert( TK_RSHIFT==OP_ShiftRight ); 2477 assert( TK_CONCAT==OP_Concat ); 2478 testcase( op==TK_AND ); 2479 testcase( op==TK_OR ); 2480 testcase( op==TK_PLUS ); 2481 testcase( op==TK_MINUS ); 2482 testcase( op==TK_REM ); 2483 testcase( op==TK_BITAND ); 2484 testcase( op==TK_BITOR ); 2485 testcase( op==TK_SLASH ); 2486 testcase( op==TK_LSHIFT ); 2487 testcase( op==TK_RSHIFT ); 2488 testcase( op==TK_CONCAT ); 2489 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 2490 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 2491 sqlite3VdbeAddOp3(v, op, r2, r1, target); 2492 testcase( regFree1==0 ); 2493 testcase( regFree2==0 ); 2494 break; 2495 } 2496 case TK_UMINUS: { 2497 Expr *pLeft = pExpr->pLeft; 2498 assert( pLeft ); 2499 if( pLeft->op==TK_INTEGER ){ 2500 codeInteger(pParse, pLeft, 1, target); 2501 #ifndef SQLITE_OMIT_FLOATING_POINT 2502 }else if( pLeft->op==TK_FLOAT ){ 2503 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2504 codeReal(v, pLeft->u.zToken, 1, target); 2505 #endif 2506 }else{ 2507 regFree1 = r1 = sqlite3GetTempReg(pParse); 2508 sqlite3VdbeAddOp2(v, OP_Integer, 0, r1); 2509 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); 2510 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); 2511 testcase( regFree2==0 ); 2512 } 2513 inReg = target; 2514 break; 2515 } 2516 case TK_BITNOT: 2517 case TK_NOT: { 2518 assert( TK_BITNOT==OP_BitNot ); 2519 assert( TK_NOT==OP_Not ); 2520 testcase( op==TK_BITNOT ); 2521 testcase( op==TK_NOT ); 2522 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 2523 testcase( regFree1==0 ); 2524 inReg = target; 2525 sqlite3VdbeAddOp2(v, op, r1, inReg); 2526 break; 2527 } 2528 case TK_ISNULL: 2529 case TK_NOTNULL: { 2530 int addr; 2531 assert( TK_ISNULL==OP_IsNull ); 2532 assert( TK_NOTNULL==OP_NotNull ); 2533 testcase( op==TK_ISNULL ); 2534 testcase( op==TK_NOTNULL ); 2535 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 2536 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 2537 testcase( regFree1==0 ); 2538 addr = sqlite3VdbeAddOp1(v, op, r1); 2539 sqlite3VdbeAddOp2(v, OP_AddImm, target, -1); 2540 sqlite3VdbeJumpHere(v, addr); 2541 break; 2542 } 2543 case TK_AGG_FUNCTION: { 2544 AggInfo *pInfo = pExpr->pAggInfo; 2545 if( pInfo==0 ){ 2546 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2547 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); 2548 }else{ 2549 inReg = pInfo->aFunc[pExpr->iAgg].iMem; 2550 } 2551 break; 2552 } 2553 case TK_CONST_FUNC: 2554 case TK_FUNCTION: { 2555 ExprList *pFarg; /* List of function arguments */ 2556 int nFarg; /* Number of function arguments */ 2557 FuncDef *pDef; /* The function definition object */ 2558 int nId; /* Length of the function name in bytes */ 2559 const char *zId; /* The function name */ 2560 int constMask = 0; /* Mask of function arguments that are constant */ 2561 int i; /* Loop counter */ 2562 u8 enc = ENC(db); /* The text encoding used by this database */ 2563 CollSeq *pColl = 0; /* A collating sequence */ 2564 2565 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 2566 testcase( op==TK_CONST_FUNC ); 2567 testcase( op==TK_FUNCTION ); 2568 if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){ 2569 pFarg = 0; 2570 }else{ 2571 pFarg = pExpr->x.pList; 2572 } 2573 nFarg = pFarg ? pFarg->nExpr : 0; 2574 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2575 zId = pExpr->u.zToken; 2576 nId = sqlite3Strlen30(zId); 2577 pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0); 2578 if( pDef==0 ){ 2579 sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId); 2580 break; 2581 } 2582 2583 /* Attempt a direct implementation of the built-in COALESCE() and 2584 ** IFNULL() functions. This avoids unnecessary evalation of 2585 ** arguments past the first non-NULL argument. 2586 */ 2587 if( pDef->flags & SQLITE_FUNC_COALESCE ){ 2588 int endCoalesce = sqlite3VdbeMakeLabel(v); 2589 assert( nFarg>=2 ); 2590 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); 2591 for(i=1; i<nFarg; i++){ 2592 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce); 2593 sqlite3ExprCacheRemove(pParse, target, 1); 2594 sqlite3ExprCachePush(pParse); 2595 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target); 2596 sqlite3ExprCachePop(pParse, 1); 2597 } 2598 sqlite3VdbeResolveLabel(v, endCoalesce); 2599 break; 2600 } 2601 2602 2603 if( pFarg ){ 2604 r1 = sqlite3GetTempRange(pParse, nFarg); 2605 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */ 2606 sqlite3ExprCodeExprList(pParse, pFarg, r1, 1); 2607 sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */ 2608 }else{ 2609 r1 = 0; 2610 } 2611 #ifndef SQLITE_OMIT_VIRTUALTABLE 2612 /* Possibly overload the function if the first argument is 2613 ** a virtual table column. 2614 ** 2615 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the 2616 ** second argument, not the first, as the argument to test to 2617 ** see if it is a column in a virtual table. This is done because 2618 ** the left operand of infix functions (the operand we want to 2619 ** control overloading) ends up as the second argument to the 2620 ** function. The expression "A glob B" is equivalent to 2621 ** "glob(B,A). We want to use the A in "A glob B" to test 2622 ** for function overloading. But we use the B term in "glob(B,A)". 2623 */ 2624 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){ 2625 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); 2626 }else if( nFarg>0 ){ 2627 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); 2628 } 2629 #endif 2630 for(i=0; i<nFarg; i++){ 2631 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){ 2632 constMask |= (1<<i); 2633 } 2634 if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ 2635 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); 2636 } 2637 } 2638 if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){ 2639 if( !pColl ) pColl = db->pDfltColl; 2640 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 2641 } 2642 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target, 2643 (char*)pDef, P4_FUNCDEF); 2644 sqlite3VdbeChangeP5(v, (u8)nFarg); 2645 if( nFarg ){ 2646 sqlite3ReleaseTempRange(pParse, r1, nFarg); 2647 } 2648 break; 2649 } 2650 #ifndef SQLITE_OMIT_SUBQUERY 2651 case TK_EXISTS: 2652 case TK_SELECT: { 2653 testcase( op==TK_EXISTS ); 2654 testcase( op==TK_SELECT ); 2655 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0); 2656 break; 2657 } 2658 case TK_IN: { 2659 int destIfFalse = sqlite3VdbeMakeLabel(v); 2660 int destIfNull = sqlite3VdbeMakeLabel(v); 2661 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 2662 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 2663 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 2664 sqlite3VdbeResolveLabel(v, destIfFalse); 2665 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); 2666 sqlite3VdbeResolveLabel(v, destIfNull); 2667 break; 2668 } 2669 #endif /* SQLITE_OMIT_SUBQUERY */ 2670 2671 2672 /* 2673 ** x BETWEEN y AND z 2674 ** 2675 ** This is equivalent to 2676 ** 2677 ** x>=y AND x<=z 2678 ** 2679 ** X is stored in pExpr->pLeft. 2680 ** Y is stored in pExpr->pList->a[0].pExpr. 2681 ** Z is stored in pExpr->pList->a[1].pExpr. 2682 */ 2683 case TK_BETWEEN: { 2684 Expr *pLeft = pExpr->pLeft; 2685 struct ExprList_item *pLItem = pExpr->x.pList->a; 2686 Expr *pRight = pLItem->pExpr; 2687 2688 r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); 2689 r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); 2690 testcase( regFree1==0 ); 2691 testcase( regFree2==0 ); 2692 r3 = sqlite3GetTempReg(pParse); 2693 r4 = sqlite3GetTempReg(pParse); 2694 codeCompare(pParse, pLeft, pRight, OP_Ge, 2695 r1, r2, r3, SQLITE_STOREP2); 2696 pLItem++; 2697 pRight = pLItem->pExpr; 2698 sqlite3ReleaseTempReg(pParse, regFree2); 2699 r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); 2700 testcase( regFree2==0 ); 2701 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2); 2702 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target); 2703 sqlite3ReleaseTempReg(pParse, r3); 2704 sqlite3ReleaseTempReg(pParse, r4); 2705 break; 2706 } 2707 case TK_UPLUS: { 2708 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); 2709 break; 2710 } 2711 2712 case TK_TRIGGER: { 2713 /* If the opcode is TK_TRIGGER, then the expression is a reference 2714 ** to a column in the new.* or old.* pseudo-tables available to 2715 ** trigger programs. In this case Expr.iTable is set to 1 for the 2716 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn 2717 ** is set to the column of the pseudo-table to read, or to -1 to 2718 ** read the rowid field. 2719 ** 2720 ** The expression is implemented using an OP_Param opcode. The p1 2721 ** parameter is set to 0 for an old.rowid reference, or to (i+1) 2722 ** to reference another column of the old.* pseudo-table, where 2723 ** i is the index of the column. For a new.rowid reference, p1 is 2724 ** set to (n+1), where n is the number of columns in each pseudo-table. 2725 ** For a reference to any other column in the new.* pseudo-table, p1 2726 ** is set to (n+2+i), where n and i are as defined previously. For 2727 ** example, if the table on which triggers are being fired is 2728 ** declared as: 2729 ** 2730 ** CREATE TABLE t1(a, b); 2731 ** 2732 ** Then p1 is interpreted as follows: 2733 ** 2734 ** p1==0 -> old.rowid p1==3 -> new.rowid 2735 ** p1==1 -> old.a p1==4 -> new.a 2736 ** p1==2 -> old.b p1==5 -> new.b 2737 */ 2738 Table *pTab = pExpr->pTab; 2739 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn; 2740 2741 assert( pExpr->iTable==0 || pExpr->iTable==1 ); 2742 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol ); 2743 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey ); 2744 assert( p1>=0 && p1<(pTab->nCol*2+2) ); 2745 2746 sqlite3VdbeAddOp2(v, OP_Param, p1, target); 2747 VdbeComment((v, "%s.%s -> $%d", 2748 (pExpr->iTable ? "new" : "old"), 2749 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName), 2750 target 2751 )); 2752 2753 #ifndef SQLITE_OMIT_FLOATING_POINT 2754 /* If the column has REAL affinity, it may currently be stored as an 2755 ** integer. Use OP_RealAffinity to make sure it is really real. */ 2756 if( pExpr->iColumn>=0 2757 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL 2758 ){ 2759 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 2760 } 2761 #endif 2762 break; 2763 } 2764 2765 2766 /* 2767 ** Form A: 2768 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 2769 ** 2770 ** Form B: 2771 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 2772 ** 2773 ** Form A is can be transformed into the equivalent form B as follows: 2774 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... 2775 ** WHEN x=eN THEN rN ELSE y END 2776 ** 2777 ** X (if it exists) is in pExpr->pLeft. 2778 ** Y is in pExpr->pRight. The Y is also optional. If there is no 2779 ** ELSE clause and no other term matches, then the result of the 2780 ** exprssion is NULL. 2781 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. 2782 ** 2783 ** The result of the expression is the Ri for the first matching Ei, 2784 ** or if there is no matching Ei, the ELSE term Y, or if there is 2785 ** no ELSE term, NULL. 2786 */ 2787 default: assert( op==TK_CASE ); { 2788 int endLabel; /* GOTO label for end of CASE stmt */ 2789 int nextCase; /* GOTO label for next WHEN clause */ 2790 int nExpr; /* 2x number of WHEN terms */ 2791 int i; /* Loop counter */ 2792 ExprList *pEList; /* List of WHEN terms */ 2793 struct ExprList_item *aListelem; /* Array of WHEN terms */ 2794 Expr opCompare; /* The X==Ei expression */ 2795 Expr cacheX; /* Cached expression X */ 2796 Expr *pX; /* The X expression */ 2797 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ 2798 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; ) 2799 2800 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); 2801 assert((pExpr->x.pList->nExpr % 2) == 0); 2802 assert(pExpr->x.pList->nExpr > 0); 2803 pEList = pExpr->x.pList; 2804 aListelem = pEList->a; 2805 nExpr = pEList->nExpr; 2806 endLabel = sqlite3VdbeMakeLabel(v); 2807 if( (pX = pExpr->pLeft)!=0 ){ 2808 cacheX = *pX; 2809 testcase( pX->op==TK_COLUMN ); 2810 testcase( pX->op==TK_REGISTER ); 2811 cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, ®Free1); 2812 testcase( regFree1==0 ); 2813 cacheX.op = TK_REGISTER; 2814 opCompare.op = TK_EQ; 2815 opCompare.pLeft = &cacheX; 2816 pTest = &opCompare; 2817 } 2818 for(i=0; i<nExpr; i=i+2){ 2819 sqlite3ExprCachePush(pParse); 2820 if( pX ){ 2821 assert( pTest!=0 ); 2822 opCompare.pRight = aListelem[i].pExpr; 2823 }else{ 2824 pTest = aListelem[i].pExpr; 2825 } 2826 nextCase = sqlite3VdbeMakeLabel(v); 2827 testcase( pTest->op==TK_COLUMN ); 2828 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); 2829 testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); 2830 testcase( aListelem[i+1].pExpr->op==TK_REGISTER ); 2831 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); 2832 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel); 2833 sqlite3ExprCachePop(pParse, 1); 2834 sqlite3VdbeResolveLabel(v, nextCase); 2835 } 2836 if( pExpr->pRight ){ 2837 sqlite3ExprCachePush(pParse); 2838 sqlite3ExprCode(pParse, pExpr->pRight, target); 2839 sqlite3ExprCachePop(pParse, 1); 2840 }else{ 2841 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 2842 } 2843 assert( db->mallocFailed || pParse->nErr>0 2844 || pParse->iCacheLevel==iCacheLevel ); 2845 sqlite3VdbeResolveLabel(v, endLabel); 2846 break; 2847 } 2848 #ifndef SQLITE_OMIT_TRIGGER 2849 case TK_RAISE: { 2850 assert( pExpr->affinity==OE_Rollback 2851 || pExpr->affinity==OE_Abort 2852 || pExpr->affinity==OE_Fail 2853 || pExpr->affinity==OE_Ignore 2854 ); 2855 if( !pParse->pTriggerTab ){ 2856 sqlite3ErrorMsg(pParse, 2857 "RAISE() may only be used within a trigger-program"); 2858 return 0; 2859 } 2860 if( pExpr->affinity==OE_Abort ){ 2861 sqlite3MayAbort(pParse); 2862 } 2863 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2864 if( pExpr->affinity==OE_Ignore ){ 2865 sqlite3VdbeAddOp4( 2866 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); 2867 }else{ 2868 sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0); 2869 } 2870 2871 break; 2872 } 2873 #endif 2874 } 2875 sqlite3ReleaseTempReg(pParse, regFree1); 2876 sqlite3ReleaseTempReg(pParse, regFree2); 2877 return inReg; 2878 } 2879 2880 /* 2881 ** Generate code to evaluate an expression and store the results 2882 ** into a register. Return the register number where the results 2883 ** are stored. 2884 ** 2885 ** If the register is a temporary register that can be deallocated, 2886 ** then write its number into *pReg. If the result register is not 2887 ** a temporary, then set *pReg to zero. 2888 */ 2889 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ 2890 int r1 = sqlite3GetTempReg(pParse); 2891 int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); 2892 if( r2==r1 ){ 2893 *pReg = r1; 2894 }else{ 2895 sqlite3ReleaseTempReg(pParse, r1); 2896 *pReg = 0; 2897 } 2898 return r2; 2899 } 2900 2901 /* 2902 ** Generate code that will evaluate expression pExpr and store the 2903 ** results in register target. The results are guaranteed to appear 2904 ** in register target. 2905 */ 2906 int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ 2907 int inReg; 2908 2909 assert( target>0 && target<=pParse->nMem ); 2910 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); 2911 assert( pParse->pVdbe || pParse->db->mallocFailed ); 2912 if( inReg!=target && pParse->pVdbe ){ 2913 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target); 2914 } 2915 return target; 2916 } 2917 2918 /* 2919 ** Generate code that evalutes the given expression and puts the result 2920 ** in register target. 2921 ** 2922 ** Also make a copy of the expression results into another "cache" register 2923 ** and modify the expression so that the next time it is evaluated, 2924 ** the result is a copy of the cache register. 2925 ** 2926 ** This routine is used for expressions that are used multiple 2927 ** times. They are evaluated once and the results of the expression 2928 ** are reused. 2929 */ 2930 int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ 2931 Vdbe *v = pParse->pVdbe; 2932 int inReg; 2933 inReg = sqlite3ExprCode(pParse, pExpr, target); 2934 assert( target>0 ); 2935 /* This routine is called for terms to INSERT or UPDATE. And the only 2936 ** other place where expressions can be converted into TK_REGISTER is 2937 ** in WHERE clause processing. So as currently implemented, there is 2938 ** no way for a TK_REGISTER to exist here. But it seems prudent to 2939 ** keep the ALWAYS() in case the conditions above change with future 2940 ** modifications or enhancements. */ 2941 if( ALWAYS(pExpr->op!=TK_REGISTER) ){ 2942 int iMem; 2943 iMem = ++pParse->nMem; 2944 sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem); 2945 pExpr->iTable = iMem; 2946 pExpr->op2 = pExpr->op; 2947 pExpr->op = TK_REGISTER; 2948 } 2949 return inReg; 2950 } 2951 2952 /* 2953 ** Return TRUE if pExpr is an constant expression that is appropriate 2954 ** for factoring out of a loop. Appropriate expressions are: 2955 ** 2956 ** * Any expression that evaluates to two or more opcodes. 2957 ** 2958 ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 2959 ** or OP_Variable that does not need to be placed in a 2960 ** specific register. 2961 ** 2962 ** There is no point in factoring out single-instruction constant 2963 ** expressions that need to be placed in a particular register. 2964 ** We could factor them out, but then we would end up adding an 2965 ** OP_SCopy instruction to move the value into the correct register 2966 ** later. We might as well just use the original instruction and 2967 ** avoid the OP_SCopy. 2968 */ 2969 static int isAppropriateForFactoring(Expr *p){ 2970 if( !sqlite3ExprIsConstantNotJoin(p) ){ 2971 return 0; /* Only constant expressions are appropriate for factoring */ 2972 } 2973 if( (p->flags & EP_FixedDest)==0 ){ 2974 return 1; /* Any constant without a fixed destination is appropriate */ 2975 } 2976 while( p->op==TK_UPLUS ) p = p->pLeft; 2977 switch( p->op ){ 2978 #ifndef SQLITE_OMIT_BLOB_LITERAL 2979 case TK_BLOB: 2980 #endif 2981 case TK_VARIABLE: 2982 case TK_INTEGER: 2983 case TK_FLOAT: 2984 case TK_NULL: 2985 case TK_STRING: { 2986 testcase( p->op==TK_BLOB ); 2987 testcase( p->op==TK_VARIABLE ); 2988 testcase( p->op==TK_INTEGER ); 2989 testcase( p->op==TK_FLOAT ); 2990 testcase( p->op==TK_NULL ); 2991 testcase( p->op==TK_STRING ); 2992 /* Single-instruction constants with a fixed destination are 2993 ** better done in-line. If we factor them, they will just end 2994 ** up generating an OP_SCopy to move the value to the destination 2995 ** register. */ 2996 return 0; 2997 } 2998 case TK_UMINUS: { 2999 if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){ 3000 return 0; 3001 } 3002 break; 3003 } 3004 default: { 3005 break; 3006 } 3007 } 3008 return 1; 3009 } 3010 3011 /* 3012 ** If pExpr is a constant expression that is appropriate for 3013 ** factoring out of a loop, then evaluate the expression 3014 ** into a register and convert the expression into a TK_REGISTER 3015 ** expression. 3016 */ 3017 static int evalConstExpr(Walker *pWalker, Expr *pExpr){ 3018 Parse *pParse = pWalker->pParse; 3019 switch( pExpr->op ){ 3020 case TK_IN: 3021 case TK_REGISTER: { 3022 return WRC_Prune; 3023 } 3024 case TK_FUNCTION: 3025 case TK_AGG_FUNCTION: 3026 case TK_CONST_FUNC: { 3027 /* The arguments to a function have a fixed destination. 3028 ** Mark them this way to avoid generated unneeded OP_SCopy 3029 ** instructions. 3030 */ 3031 ExprList *pList = pExpr->x.pList; 3032 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 3033 if( pList ){ 3034 int i = pList->nExpr; 3035 struct ExprList_item *pItem = pList->a; 3036 for(; i>0; i--, pItem++){ 3037 if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest; 3038 } 3039 } 3040 break; 3041 } 3042 } 3043 if( isAppropriateForFactoring(pExpr) ){ 3044 int r1 = ++pParse->nMem; 3045 int r2; 3046 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); 3047 if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1); 3048 pExpr->op2 = pExpr->op; 3049 pExpr->op = TK_REGISTER; 3050 pExpr->iTable = r2; 3051 return WRC_Prune; 3052 } 3053 return WRC_Continue; 3054 } 3055 3056 /* 3057 ** Preevaluate constant subexpressions within pExpr and store the 3058 ** results in registers. Modify pExpr so that the constant subexpresions 3059 ** are TK_REGISTER opcodes that refer to the precomputed values. 3060 */ 3061 void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){ 3062 Walker w; 3063 w.xExprCallback = evalConstExpr; 3064 w.xSelectCallback = 0; 3065 w.pParse = pParse; 3066 sqlite3WalkExpr(&w, pExpr); 3067 } 3068 3069 3070 /* 3071 ** Generate code that pushes the value of every element of the given 3072 ** expression list into a sequence of registers beginning at target. 3073 ** 3074 ** Return the number of elements evaluated. 3075 */ 3076 int sqlite3ExprCodeExprList( 3077 Parse *pParse, /* Parsing context */ 3078 ExprList *pList, /* The expression list to be coded */ 3079 int target, /* Where to write results */ 3080 int doHardCopy /* Make a hard copy of every element */ 3081 ){ 3082 struct ExprList_item *pItem; 3083 int i, n; 3084 assert( pList!=0 ); 3085 assert( target>0 ); 3086 n = pList->nExpr; 3087 for(pItem=pList->a, i=0; i<n; i++, pItem++){ 3088 if( pItem->iAlias ){ 3089 int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i); 3090 Vdbe *v = sqlite3GetVdbe(pParse); 3091 if( iReg!=target+i ){ 3092 sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i); 3093 } 3094 }else{ 3095 sqlite3ExprCode(pParse, pItem->pExpr, target+i); 3096 } 3097 if( doHardCopy && !pParse->db->mallocFailed ){ 3098 sqlite3ExprHardCopy(pParse, target, n); 3099 } 3100 } 3101 return n; 3102 } 3103 3104 /* 3105 ** Generate code for a BETWEEN operator. 3106 ** 3107 ** x BETWEEN y AND z 3108 ** 3109 ** The above is equivalent to 3110 ** 3111 ** x>=y AND x<=z 3112 ** 3113 ** Code it as such, taking care to do the common subexpression 3114 ** elementation of x. 3115 */ 3116 static void exprCodeBetween( 3117 Parse *pParse, /* Parsing and code generating context */ 3118 Expr *pExpr, /* The BETWEEN expression */ 3119 int dest, /* Jump here if the jump is taken */ 3120 int jumpIfTrue, /* Take the jump if the BETWEEN is true */ 3121 int jumpIfNull /* Take the jump if the BETWEEN is NULL */ 3122 ){ 3123 Expr exprAnd; /* The AND operator in x>=y AND x<=z */ 3124 Expr compLeft; /* The x>=y term */ 3125 Expr compRight; /* The x<=z term */ 3126 Expr exprX; /* The x subexpression */ 3127 int regFree1 = 0; /* Temporary use register */ 3128 3129 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 3130 exprX = *pExpr->pLeft; 3131 exprAnd.op = TK_AND; 3132 exprAnd.pLeft = &compLeft; 3133 exprAnd.pRight = &compRight; 3134 compLeft.op = TK_GE; 3135 compLeft.pLeft = &exprX; 3136 compLeft.pRight = pExpr->x.pList->a[0].pExpr; 3137 compRight.op = TK_LE; 3138 compRight.pLeft = &exprX; 3139 compRight.pRight = pExpr->x.pList->a[1].pExpr; 3140 exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, ®Free1); 3141 exprX.op = TK_REGISTER; 3142 if( jumpIfTrue ){ 3143 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull); 3144 }else{ 3145 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull); 3146 } 3147 sqlite3ReleaseTempReg(pParse, regFree1); 3148 3149 /* Ensure adequate test coverage */ 3150 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 ); 3151 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 ); 3152 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 ); 3153 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 ); 3154 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 ); 3155 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 ); 3156 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 ); 3157 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 ); 3158 } 3159 3160 /* 3161 ** Generate code for a boolean expression such that a jump is made 3162 ** to the label "dest" if the expression is true but execution 3163 ** continues straight thru if the expression is false. 3164 ** 3165 ** If the expression evaluates to NULL (neither true nor false), then 3166 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. 3167 ** 3168 ** This code depends on the fact that certain token values (ex: TK_EQ) 3169 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding 3170 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in 3171 ** the make process cause these values to align. Assert()s in the code 3172 ** below verify that the numbers are aligned correctly. 3173 */ 3174 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 3175 Vdbe *v = pParse->pVdbe; 3176 int op = 0; 3177 int regFree1 = 0; 3178 int regFree2 = 0; 3179 int r1, r2; 3180 3181 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 3182 if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */ 3183 if( NEVER(pExpr==0) ) return; /* No way this can happen */ 3184 op = pExpr->op; 3185 switch( op ){ 3186 case TK_AND: { 3187 int d2 = sqlite3VdbeMakeLabel(v); 3188 testcase( jumpIfNull==0 ); 3189 sqlite3ExprCachePush(pParse); 3190 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); 3191 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 3192 sqlite3VdbeResolveLabel(v, d2); 3193 sqlite3ExprCachePop(pParse, 1); 3194 break; 3195 } 3196 case TK_OR: { 3197 testcase( jumpIfNull==0 ); 3198 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 3199 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 3200 break; 3201 } 3202 case TK_NOT: { 3203 testcase( jumpIfNull==0 ); 3204 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 3205 break; 3206 } 3207 case TK_LT: 3208 case TK_LE: 3209 case TK_GT: 3210 case TK_GE: 3211 case TK_NE: 3212 case TK_EQ: { 3213 assert( TK_LT==OP_Lt ); 3214 assert( TK_LE==OP_Le ); 3215 assert( TK_GT==OP_Gt ); 3216 assert( TK_GE==OP_Ge ); 3217 assert( TK_EQ==OP_Eq ); 3218 assert( TK_NE==OP_Ne ); 3219 testcase( op==TK_LT ); 3220 testcase( op==TK_LE ); 3221 testcase( op==TK_GT ); 3222 testcase( op==TK_GE ); 3223 testcase( op==TK_EQ ); 3224 testcase( op==TK_NE ); 3225 testcase( jumpIfNull==0 ); 3226 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3227 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 3228 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 3229 r1, r2, dest, jumpIfNull); 3230 testcase( regFree1==0 ); 3231 testcase( regFree2==0 ); 3232 break; 3233 } 3234 case TK_IS: 3235 case TK_ISNOT: { 3236 testcase( op==TK_IS ); 3237 testcase( op==TK_ISNOT ); 3238 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3239 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 3240 op = (op==TK_IS) ? TK_EQ : TK_NE; 3241 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 3242 r1, r2, dest, SQLITE_NULLEQ); 3243 testcase( regFree1==0 ); 3244 testcase( regFree2==0 ); 3245 break; 3246 } 3247 case TK_ISNULL: 3248 case TK_NOTNULL: { 3249 assert( TK_ISNULL==OP_IsNull ); 3250 assert( TK_NOTNULL==OP_NotNull ); 3251 testcase( op==TK_ISNULL ); 3252 testcase( op==TK_NOTNULL ); 3253 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3254 sqlite3VdbeAddOp2(v, op, r1, dest); 3255 testcase( regFree1==0 ); 3256 break; 3257 } 3258 case TK_BETWEEN: { 3259 testcase( jumpIfNull==0 ); 3260 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull); 3261 break; 3262 } 3263 case TK_IN: { 3264 int destIfFalse = sqlite3VdbeMakeLabel(v); 3265 int destIfNull = jumpIfNull ? dest : destIfFalse; 3266 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 3267 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest); 3268 sqlite3VdbeResolveLabel(v, destIfFalse); 3269 break; 3270 } 3271 default: { 3272 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 3273 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); 3274 testcase( regFree1==0 ); 3275 testcase( jumpIfNull==0 ); 3276 break; 3277 } 3278 } 3279 sqlite3ReleaseTempReg(pParse, regFree1); 3280 sqlite3ReleaseTempReg(pParse, regFree2); 3281 } 3282 3283 /* 3284 ** Generate code for a boolean expression such that a jump is made 3285 ** to the label "dest" if the expression is false but execution 3286 ** continues straight thru if the expression is true. 3287 ** 3288 ** If the expression evaluates to NULL (neither true nor false) then 3289 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull 3290 ** is 0. 3291 */ 3292 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 3293 Vdbe *v = pParse->pVdbe; 3294 int op = 0; 3295 int regFree1 = 0; 3296 int regFree2 = 0; 3297 int r1, r2; 3298 3299 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 3300 if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */ 3301 if( pExpr==0 ) return; 3302 3303 /* The value of pExpr->op and op are related as follows: 3304 ** 3305 ** pExpr->op op 3306 ** --------- ---------- 3307 ** TK_ISNULL OP_NotNull 3308 ** TK_NOTNULL OP_IsNull 3309 ** TK_NE OP_Eq 3310 ** TK_EQ OP_Ne 3311 ** TK_GT OP_Le 3312 ** TK_LE OP_Gt 3313 ** TK_GE OP_Lt 3314 ** TK_LT OP_Ge 3315 ** 3316 ** For other values of pExpr->op, op is undefined and unused. 3317 ** The value of TK_ and OP_ constants are arranged such that we 3318 ** can compute the mapping above using the following expression. 3319 ** Assert()s verify that the computation is correct. 3320 */ 3321 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); 3322 3323 /* Verify correct alignment of TK_ and OP_ constants 3324 */ 3325 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); 3326 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); 3327 assert( pExpr->op!=TK_NE || op==OP_Eq ); 3328 assert( pExpr->op!=TK_EQ || op==OP_Ne ); 3329 assert( pExpr->op!=TK_LT || op==OP_Ge ); 3330 assert( pExpr->op!=TK_LE || op==OP_Gt ); 3331 assert( pExpr->op!=TK_GT || op==OP_Le ); 3332 assert( pExpr->op!=TK_GE || op==OP_Lt ); 3333 3334 switch( pExpr->op ){ 3335 case TK_AND: { 3336 testcase( jumpIfNull==0 ); 3337 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 3338 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 3339 break; 3340 } 3341 case TK_OR: { 3342 int d2 = sqlite3VdbeMakeLabel(v); 3343 testcase( jumpIfNull==0 ); 3344 sqlite3ExprCachePush(pParse); 3345 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); 3346 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 3347 sqlite3VdbeResolveLabel(v, d2); 3348 sqlite3ExprCachePop(pParse, 1); 3349 break; 3350 } 3351 case TK_NOT: { 3352 testcase( jumpIfNull==0 ); 3353 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 3354 break; 3355 } 3356 case TK_LT: 3357 case TK_LE: 3358 case TK_GT: 3359 case TK_GE: 3360 case TK_NE: 3361 case TK_EQ: { 3362 testcase( op==TK_LT ); 3363 testcase( op==TK_LE ); 3364 testcase( op==TK_GT ); 3365 testcase( op==TK_GE ); 3366 testcase( op==TK_EQ ); 3367 testcase( op==TK_NE ); 3368 testcase( jumpIfNull==0 ); 3369 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3370 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 3371 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 3372 r1, r2, dest, jumpIfNull); 3373 testcase( regFree1==0 ); 3374 testcase( regFree2==0 ); 3375 break; 3376 } 3377 case TK_IS: 3378 case TK_ISNOT: { 3379 testcase( pExpr->op==TK_IS ); 3380 testcase( pExpr->op==TK_ISNOT ); 3381 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3382 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 3383 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; 3384 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 3385 r1, r2, dest, SQLITE_NULLEQ); 3386 testcase( regFree1==0 ); 3387 testcase( regFree2==0 ); 3388 break; 3389 } 3390 case TK_ISNULL: 3391 case TK_NOTNULL: { 3392 testcase( op==TK_ISNULL ); 3393 testcase( op==TK_NOTNULL ); 3394 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 3395 sqlite3VdbeAddOp2(v, op, r1, dest); 3396 testcase( regFree1==0 ); 3397 break; 3398 } 3399 case TK_BETWEEN: { 3400 testcase( jumpIfNull==0 ); 3401 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull); 3402 break; 3403 } 3404 case TK_IN: { 3405 if( jumpIfNull ){ 3406 sqlite3ExprCodeIN(pParse, pExpr, dest, dest); 3407 }else{ 3408 int destIfNull = sqlite3VdbeMakeLabel(v); 3409 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); 3410 sqlite3VdbeResolveLabel(v, destIfNull); 3411 } 3412 break; 3413 } 3414 default: { 3415 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 3416 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); 3417 testcase( regFree1==0 ); 3418 testcase( jumpIfNull==0 ); 3419 break; 3420 } 3421 } 3422 sqlite3ReleaseTempReg(pParse, regFree1); 3423 sqlite3ReleaseTempReg(pParse, regFree2); 3424 } 3425 3426 /* 3427 ** Do a deep comparison of two expression trees. Return 0 if the two 3428 ** expressions are completely identical. Return 1 if they differ only 3429 ** by a COLLATE operator at the top level. Return 2 if there are differences 3430 ** other than the top-level COLLATE operator. 3431 ** 3432 ** Sometimes this routine will return 2 even if the two expressions 3433 ** really are equivalent. If we cannot prove that the expressions are 3434 ** identical, we return 2 just to be safe. So if this routine 3435 ** returns 2, then you do not really know for certain if the two 3436 ** expressions are the same. But if you get a 0 or 1 return, then you 3437 ** can be sure the expressions are the same. In the places where 3438 ** this routine is used, it does not hurt to get an extra 2 - that 3439 ** just might result in some slightly slower code. But returning 3440 ** an incorrect 0 or 1 could lead to a malfunction. 3441 */ 3442 int sqlite3ExprCompare(Expr *pA, Expr *pB){ 3443 if( pA==0||pB==0 ){ 3444 return pB==pA ? 0 : 2; 3445 } 3446 assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) ); 3447 assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) ); 3448 if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){ 3449 return 2; 3450 } 3451 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2; 3452 if( pA->op!=pB->op ) return 2; 3453 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2; 3454 if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2; 3455 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2; 3456 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2; 3457 if( ExprHasProperty(pA, EP_IntValue) ){ 3458 if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){ 3459 return 2; 3460 } 3461 }else if( pA->op!=TK_COLUMN && pA->u.zToken ){ 3462 if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2; 3463 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){ 3464 return 2; 3465 } 3466 } 3467 if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1; 3468 if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2; 3469 return 0; 3470 } 3471 3472 /* 3473 ** Compare two ExprList objects. Return 0 if they are identical and 3474 ** non-zero if they differ in any way. 3475 ** 3476 ** This routine might return non-zero for equivalent ExprLists. The 3477 ** only consequence will be disabled optimizations. But this routine 3478 ** must never return 0 if the two ExprList objects are different, or 3479 ** a malfunction will result. 3480 ** 3481 ** Two NULL pointers are considered to be the same. But a NULL pointer 3482 ** always differs from a non-NULL pointer. 3483 */ 3484 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){ 3485 int i; 3486 if( pA==0 && pB==0 ) return 0; 3487 if( pA==0 || pB==0 ) return 1; 3488 if( pA->nExpr!=pB->nExpr ) return 1; 3489 for(i=0; i<pA->nExpr; i++){ 3490 Expr *pExprA = pA->a[i].pExpr; 3491 Expr *pExprB = pB->a[i].pExpr; 3492 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1; 3493 if( sqlite3ExprCompare(pExprA, pExprB) ) return 1; 3494 } 3495 return 0; 3496 } 3497 3498 /* 3499 ** Add a new element to the pAggInfo->aCol[] array. Return the index of 3500 ** the new element. Return a negative number if malloc fails. 3501 */ 3502 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ 3503 int i; 3504 pInfo->aCol = sqlite3ArrayAllocate( 3505 db, 3506 pInfo->aCol, 3507 sizeof(pInfo->aCol[0]), 3508 3, 3509 &pInfo->nColumn, 3510 &pInfo->nColumnAlloc, 3511 &i 3512 ); 3513 return i; 3514 } 3515 3516 /* 3517 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of 3518 ** the new element. Return a negative number if malloc fails. 3519 */ 3520 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ 3521 int i; 3522 pInfo->aFunc = sqlite3ArrayAllocate( 3523 db, 3524 pInfo->aFunc, 3525 sizeof(pInfo->aFunc[0]), 3526 3, 3527 &pInfo->nFunc, 3528 &pInfo->nFuncAlloc, 3529 &i 3530 ); 3531 return i; 3532 } 3533 3534 /* 3535 ** This is the xExprCallback for a tree walker. It is used to 3536 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates 3537 ** for additional information. 3538 */ 3539 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ 3540 int i; 3541 NameContext *pNC = pWalker->u.pNC; 3542 Parse *pParse = pNC->pParse; 3543 SrcList *pSrcList = pNC->pSrcList; 3544 AggInfo *pAggInfo = pNC->pAggInfo; 3545 3546 switch( pExpr->op ){ 3547 case TK_AGG_COLUMN: 3548 case TK_COLUMN: { 3549 testcase( pExpr->op==TK_AGG_COLUMN ); 3550 testcase( pExpr->op==TK_COLUMN ); 3551 /* Check to see if the column is in one of the tables in the FROM 3552 ** clause of the aggregate query */ 3553 if( ALWAYS(pSrcList!=0) ){ 3554 struct SrcList_item *pItem = pSrcList->a; 3555 for(i=0; i<pSrcList->nSrc; i++, pItem++){ 3556 struct AggInfo_col *pCol; 3557 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 3558 if( pExpr->iTable==pItem->iCursor ){ 3559 /* If we reach this point, it means that pExpr refers to a table 3560 ** that is in the FROM clause of the aggregate query. 3561 ** 3562 ** Make an entry for the column in pAggInfo->aCol[] if there 3563 ** is not an entry there already. 3564 */ 3565 int k; 3566 pCol = pAggInfo->aCol; 3567 for(k=0; k<pAggInfo->nColumn; k++, pCol++){ 3568 if( pCol->iTable==pExpr->iTable && 3569 pCol->iColumn==pExpr->iColumn ){ 3570 break; 3571 } 3572 } 3573 if( (k>=pAggInfo->nColumn) 3574 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 3575 ){ 3576 pCol = &pAggInfo->aCol[k]; 3577 pCol->pTab = pExpr->pTab; 3578 pCol->iTable = pExpr->iTable; 3579 pCol->iColumn = pExpr->iColumn; 3580 pCol->iMem = ++pParse->nMem; 3581 pCol->iSorterColumn = -1; 3582 pCol->pExpr = pExpr; 3583 if( pAggInfo->pGroupBy ){ 3584 int j, n; 3585 ExprList *pGB = pAggInfo->pGroupBy; 3586 struct ExprList_item *pTerm = pGB->a; 3587 n = pGB->nExpr; 3588 for(j=0; j<n; j++, pTerm++){ 3589 Expr *pE = pTerm->pExpr; 3590 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && 3591 pE->iColumn==pExpr->iColumn ){ 3592 pCol->iSorterColumn = j; 3593 break; 3594 } 3595 } 3596 } 3597 if( pCol->iSorterColumn<0 ){ 3598 pCol->iSorterColumn = pAggInfo->nSortingColumn++; 3599 } 3600 } 3601 /* There is now an entry for pExpr in pAggInfo->aCol[] (either 3602 ** because it was there before or because we just created it). 3603 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that 3604 ** pAggInfo->aCol[] entry. 3605 */ 3606 ExprSetIrreducible(pExpr); 3607 pExpr->pAggInfo = pAggInfo; 3608 pExpr->op = TK_AGG_COLUMN; 3609 pExpr->iAgg = (i16)k; 3610 break; 3611 } /* endif pExpr->iTable==pItem->iCursor */ 3612 } /* end loop over pSrcList */ 3613 } 3614 return WRC_Prune; 3615 } 3616 case TK_AGG_FUNCTION: { 3617 /* The pNC->nDepth==0 test causes aggregate functions in subqueries 3618 ** to be ignored */ 3619 if( pNC->nDepth==0 ){ 3620 /* Check to see if pExpr is a duplicate of another aggregate 3621 ** function that is already in the pAggInfo structure 3622 */ 3623 struct AggInfo_func *pItem = pAggInfo->aFunc; 3624 for(i=0; i<pAggInfo->nFunc; i++, pItem++){ 3625 if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){ 3626 break; 3627 } 3628 } 3629 if( i>=pAggInfo->nFunc ){ 3630 /* pExpr is original. Make a new entry in pAggInfo->aFunc[] 3631 */ 3632 u8 enc = ENC(pParse->db); 3633 i = addAggInfoFunc(pParse->db, pAggInfo); 3634 if( i>=0 ){ 3635 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 3636 pItem = &pAggInfo->aFunc[i]; 3637 pItem->pExpr = pExpr; 3638 pItem->iMem = ++pParse->nMem; 3639 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 3640 pItem->pFunc = sqlite3FindFunction(pParse->db, 3641 pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken), 3642 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); 3643 if( pExpr->flags & EP_Distinct ){ 3644 pItem->iDistinct = pParse->nTab++; 3645 }else{ 3646 pItem->iDistinct = -1; 3647 } 3648 } 3649 } 3650 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry 3651 */ 3652 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 3653 ExprSetIrreducible(pExpr); 3654 pExpr->iAgg = (i16)i; 3655 pExpr->pAggInfo = pAggInfo; 3656 return WRC_Prune; 3657 } 3658 } 3659 } 3660 return WRC_Continue; 3661 } 3662 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){ 3663 NameContext *pNC = pWalker->u.pNC; 3664 if( pNC->nDepth==0 ){ 3665 pNC->nDepth++; 3666 sqlite3WalkSelect(pWalker, pSelect); 3667 pNC->nDepth--; 3668 return WRC_Prune; 3669 }else{ 3670 return WRC_Continue; 3671 } 3672 } 3673 3674 /* 3675 ** Analyze the given expression looking for aggregate functions and 3676 ** for variables that need to be added to the pParse->aAgg[] array. 3677 ** Make additional entries to the pParse->aAgg[] array as necessary. 3678 ** 3679 ** This routine should only be called after the expression has been 3680 ** analyzed by sqlite3ResolveExprNames(). 3681 */ 3682 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ 3683 Walker w; 3684 w.xExprCallback = analyzeAggregate; 3685 w.xSelectCallback = analyzeAggregatesInSelect; 3686 w.u.pNC = pNC; 3687 assert( pNC->pSrcList!=0 ); 3688 sqlite3WalkExpr(&w, pExpr); 3689 } 3690 3691 /* 3692 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an 3693 ** expression list. Return the number of errors. 3694 ** 3695 ** If an error is found, the analysis is cut short. 3696 */ 3697 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ 3698 struct ExprList_item *pItem; 3699 int i; 3700 if( pList ){ 3701 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ 3702 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); 3703 } 3704 } 3705 } 3706 3707 /* 3708 ** Allocate a single new register for use to hold some intermediate result. 3709 */ 3710 int sqlite3GetTempReg(Parse *pParse){ 3711 if( pParse->nTempReg==0 ){ 3712 return ++pParse->nMem; 3713 } 3714 return pParse->aTempReg[--pParse->nTempReg]; 3715 } 3716 3717 /* 3718 ** Deallocate a register, making available for reuse for some other 3719 ** purpose. 3720 ** 3721 ** If a register is currently being used by the column cache, then 3722 ** the dallocation is deferred until the column cache line that uses 3723 ** the register becomes stale. 3724 */ 3725 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ 3726 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){ 3727 int i; 3728 struct yColCache *p; 3729 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){ 3730 if( p->iReg==iReg ){ 3731 p->tempReg = 1; 3732 return; 3733 } 3734 } 3735 pParse->aTempReg[pParse->nTempReg++] = iReg; 3736 } 3737 } 3738 3739 /* 3740 ** Allocate or deallocate a block of nReg consecutive registers 3741 */ 3742 int sqlite3GetTempRange(Parse *pParse, int nReg){ 3743 int i, n; 3744 i = pParse->iRangeReg; 3745 n = pParse->nRangeReg; 3746 if( nReg<=n ){ 3747 assert( !usedAsColumnCache(pParse, i, i+n-1) ); 3748 pParse->iRangeReg += nReg; 3749 pParse->nRangeReg -= nReg; 3750 }else{ 3751 i = pParse->nMem+1; 3752 pParse->nMem += nReg; 3753 } 3754 return i; 3755 } 3756 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ 3757 sqlite3ExprCacheRemove(pParse, iReg, nReg); 3758 if( nReg>pParse->nRangeReg ){ 3759 pParse->nRangeReg = nReg; 3760 pParse->iRangeReg = iReg; 3761 } 3762 } 3763