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