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