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.308 2007/08/22 20:18:22 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 CollSeq *pColl; 58 if( pExpr==0 ) return 0; 59 pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n); 60 if( pColl ){ 61 pExpr->pColl = pColl; 62 pExpr->flags |= EP_ExpCollate; 63 } 64 return pExpr; 65 } 66 67 /* 68 ** Return the default collation sequence for the expression pExpr. If 69 ** there is no default collation type, return 0. 70 */ 71 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){ 72 CollSeq *pColl = 0; 73 if( pExpr ){ 74 int op; 75 pColl = pExpr->pColl; 76 op = pExpr->op; 77 if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){ 78 return sqlite3ExprCollSeq(pParse, pExpr->pLeft); 79 } 80 } 81 if( sqlite3CheckCollSeq(pParse, pColl) ){ 82 pColl = 0; 83 } 84 return pColl; 85 } 86 87 /* 88 ** pExpr is an operand of a comparison operator. aff2 is the 89 ** type affinity of the other operand. This routine returns the 90 ** type affinity that should be used for the comparison operator. 91 */ 92 char sqlite3CompareAffinity(Expr *pExpr, char aff2){ 93 char aff1 = sqlite3ExprAffinity(pExpr); 94 if( aff1 && aff2 ){ 95 /* Both sides of the comparison are columns. If one has numeric 96 ** affinity, use that. Otherwise use no affinity. 97 */ 98 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ 99 return SQLITE_AFF_NUMERIC; 100 }else{ 101 return SQLITE_AFF_NONE; 102 } 103 }else if( !aff1 && !aff2 ){ 104 /* Neither side of the comparison is a column. Compare the 105 ** results directly. 106 */ 107 return SQLITE_AFF_NONE; 108 }else{ 109 /* One side is a column, the other is not. Use the columns affinity. */ 110 assert( aff1==0 || aff2==0 ); 111 return (aff1 + aff2); 112 } 113 } 114 115 /* 116 ** pExpr is a comparison operator. Return the type affinity that should 117 ** be applied to both operands prior to doing the comparison. 118 */ 119 static char comparisonAffinity(Expr *pExpr){ 120 char aff; 121 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || 122 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || 123 pExpr->op==TK_NE ); 124 assert( pExpr->pLeft ); 125 aff = sqlite3ExprAffinity(pExpr->pLeft); 126 if( pExpr->pRight ){ 127 aff = sqlite3CompareAffinity(pExpr->pRight, aff); 128 } 129 else if( pExpr->pSelect ){ 130 aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff); 131 } 132 else if( !aff ){ 133 aff = SQLITE_AFF_NONE; 134 } 135 return aff; 136 } 137 138 /* 139 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. 140 ** idx_affinity is the affinity of an indexed column. Return true 141 ** if the index with affinity idx_affinity may be used to implement 142 ** the comparison in pExpr. 143 */ 144 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){ 145 char aff = comparisonAffinity(pExpr); 146 switch( aff ){ 147 case SQLITE_AFF_NONE: 148 return 1; 149 case SQLITE_AFF_TEXT: 150 return idx_affinity==SQLITE_AFF_TEXT; 151 default: 152 return sqlite3IsNumericAffinity(idx_affinity); 153 } 154 } 155 156 /* 157 ** Return the P1 value that should be used for a binary comparison 158 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. 159 ** If jumpIfNull is true, then set the low byte of the returned 160 ** P1 value to tell the opcode to jump if either expression 161 ** evaluates to NULL. 162 */ 163 static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ 164 char aff = sqlite3ExprAffinity(pExpr2); 165 return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0); 166 } 167 168 /* 169 ** Return a pointer to the collation sequence that should be used by 170 ** a binary comparison operator comparing pLeft and pRight. 171 ** 172 ** If the left hand expression has a collating sequence type, then it is 173 ** used. Otherwise the collation sequence for the right hand expression 174 ** is used, or the default (BINARY) if neither expression has a collating 175 ** type. 176 ** 177 ** Argument pRight (but not pLeft) may be a null pointer. In this case, 178 ** it is not considered. 179 */ 180 CollSeq *sqlite3BinaryCompareCollSeq( 181 Parse *pParse, 182 Expr *pLeft, 183 Expr *pRight 184 ){ 185 CollSeq *pColl; 186 assert( pLeft ); 187 if( pLeft->flags & EP_ExpCollate ){ 188 assert( pLeft->pColl ); 189 pColl = pLeft->pColl; 190 }else if( pRight && pRight->flags & EP_ExpCollate ){ 191 assert( pRight->pColl ); 192 pColl = pRight->pColl; 193 }else{ 194 pColl = sqlite3ExprCollSeq(pParse, pLeft); 195 if( !pColl ){ 196 pColl = sqlite3ExprCollSeq(pParse, pRight); 197 } 198 } 199 return pColl; 200 } 201 202 /* 203 ** Generate code for a comparison operator. 204 */ 205 static int codeCompare( 206 Parse *pParse, /* The parsing (and code generating) context */ 207 Expr *pLeft, /* The left operand */ 208 Expr *pRight, /* The right operand */ 209 int opcode, /* The comparison opcode */ 210 int dest, /* Jump here if true. */ 211 int jumpIfNull /* If true, jump if either operand is NULL */ 212 ){ 213 int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull); 214 CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); 215 return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ); 216 } 217 218 /* 219 ** Construct a new expression node and return a pointer to it. Memory 220 ** for this node is obtained from sqlite3_malloc(). The calling function 221 ** is responsible for making sure the node eventually gets freed. 222 */ 223 Expr *sqlite3Expr( 224 int op, /* Expression opcode */ 225 Expr *pLeft, /* Left operand */ 226 Expr *pRight, /* Right operand */ 227 const Token *pToken /* Argument token */ 228 ){ 229 Expr *pNew; 230 pNew = sqlite3MallocZero( sizeof(Expr) ); 231 if( pNew==0 ){ 232 /* When malloc fails, delete pLeft and pRight. Expressions passed to 233 ** this function must always be allocated with sqlite3Expr() for this 234 ** reason. 235 */ 236 sqlite3ExprDelete(pLeft); 237 sqlite3ExprDelete(pRight); 238 return 0; 239 } 240 pNew->op = op; 241 pNew->pLeft = pLeft; 242 pNew->pRight = pRight; 243 pNew->iAgg = -1; 244 if( pToken ){ 245 assert( pToken->dyn==0 ); 246 pNew->span = pNew->token = *pToken; 247 }else if( pLeft ){ 248 if( pRight ){ 249 sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span); 250 if( pRight->flags & EP_ExpCollate ){ 251 pNew->flags |= EP_ExpCollate; 252 pNew->pColl = pRight->pColl; 253 } 254 } 255 if( pLeft->flags & EP_ExpCollate ){ 256 pNew->flags |= EP_ExpCollate; 257 pNew->pColl = pLeft->pColl; 258 } 259 } 260 261 sqlite3ExprSetHeight(pNew); 262 return pNew; 263 } 264 265 /* 266 ** Works like sqlite3Expr() except that it takes an extra Parse* 267 ** argument and notifies the associated connection object if malloc fails. 268 */ 269 Expr *sqlite3PExpr( 270 Parse *pParse, /* Parsing context */ 271 int op, /* Expression opcode */ 272 Expr *pLeft, /* Left operand */ 273 Expr *pRight, /* Right operand */ 274 const Token *pToken /* Argument token */ 275 ){ 276 Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken); 277 if( pNew==0 ){ 278 pParse->db->mallocFailed = 1; 279 } 280 return pNew; 281 } 282 283 /* 284 ** When doing a nested parse, you can include terms in an expression 285 ** that look like this: #0 #1 #2 ... These terms refer to elements 286 ** on the stack. "#0" means the top of the stack. 287 ** "#1" means the next down on the stack. And so forth. 288 ** 289 ** This routine is called by the parser to deal with on of those terms. 290 ** It immediately generates code to store the value in a memory location. 291 ** The returns an expression that will code to extract the value from 292 ** that memory location as needed. 293 */ 294 Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){ 295 Vdbe *v = pParse->pVdbe; 296 Expr *p; 297 int depth; 298 if( pParse->nested==0 ){ 299 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken); 300 return sqlite3Expr(TK_NULL, 0, 0, 0); 301 } 302 if( v==0 ) return 0; 303 p = sqlite3Expr(TK_REGISTER, 0, 0, pToken); 304 if( p==0 ){ 305 pParse->db->mallocFailed = 1; 306 return 0; /* Malloc failed */ 307 } 308 depth = atoi((char*)&pToken->z[1]); 309 p->iTable = pParse->nMem++; 310 sqlite3VdbeAddOp(v, OP_Dup, depth, 0); 311 sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1); 312 return p; 313 } 314 315 /* 316 ** Join two expressions using an AND operator. If either expression is 317 ** NULL, then just return the other expression. 318 */ 319 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){ 320 if( pLeft==0 ){ 321 return pRight; 322 }else if( pRight==0 ){ 323 return pLeft; 324 }else{ 325 Expr *p = sqlite3Expr(TK_AND, pLeft, pRight, 0); 326 if( p==0 ){ 327 db->mallocFailed = 1; 328 } 329 return p; 330 } 331 } 332 333 /* 334 ** Set the Expr.span field of the given expression to span all 335 ** text between the two given tokens. 336 */ 337 void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){ 338 assert( pRight!=0 ); 339 assert( pLeft!=0 ); 340 if( pExpr && pRight->z && pLeft->z ){ 341 assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 ); 342 if( pLeft->dyn==0 && pRight->dyn==0 ){ 343 pExpr->span.z = pLeft->z; 344 pExpr->span.n = pRight->n + (pRight->z - pLeft->z); 345 }else{ 346 pExpr->span.z = 0; 347 } 348 } 349 } 350 351 /* 352 ** Construct a new expression node for a function with multiple 353 ** arguments. 354 */ 355 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){ 356 Expr *pNew; 357 assert( pToken ); 358 pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) ); 359 if( pNew==0 ){ 360 sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */ 361 return 0; 362 } 363 pNew->op = TK_FUNCTION; 364 pNew->pList = pList; 365 assert( pToken->dyn==0 ); 366 pNew->token = *pToken; 367 pNew->span = pNew->token; 368 369 sqlite3ExprSetHeight(pNew); 370 return pNew; 371 } 372 373 /* 374 ** Assign a variable number to an expression that encodes a wildcard 375 ** in the original SQL statement. 376 ** 377 ** Wildcards consisting of a single "?" are assigned the next sequential 378 ** variable number. 379 ** 380 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make 381 ** sure "nnn" is not too be to avoid a denial of service attack when 382 ** the SQL statement comes from an external source. 383 ** 384 ** Wildcards of the form ":aaa" or "$aaa" are assigned the same number 385 ** as the previous instance of the same wildcard. Or if this is the first 386 ** instance of the wildcard, the next sequenial variable number is 387 ** assigned. 388 */ 389 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){ 390 Token *pToken; 391 sqlite3 *db = pParse->db; 392 393 if( pExpr==0 ) return; 394 pToken = &pExpr->token; 395 assert( pToken->n>=1 ); 396 assert( pToken->z!=0 ); 397 assert( pToken->z[0]!=0 ); 398 if( pToken->n==1 ){ 399 /* Wildcard of the form "?". Assign the next variable number */ 400 pExpr->iTable = ++pParse->nVar; 401 }else if( pToken->z[0]=='?' ){ 402 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and 403 ** use it as the variable number */ 404 int i; 405 pExpr->iTable = i = atoi((char*)&pToken->z[1]); 406 if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){ 407 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", 408 SQLITE_MAX_VARIABLE_NUMBER); 409 } 410 if( i>pParse->nVar ){ 411 pParse->nVar = i; 412 } 413 }else{ 414 /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable 415 ** number as the prior appearance of the same name, or if the name 416 ** has never appeared before, reuse the same variable number 417 */ 418 int i, n; 419 n = pToken->n; 420 for(i=0; i<pParse->nVarExpr; i++){ 421 Expr *pE; 422 if( (pE = pParse->apVarExpr[i])!=0 423 && pE->token.n==n 424 && memcmp(pE->token.z, pToken->z, n)==0 ){ 425 pExpr->iTable = pE->iTable; 426 break; 427 } 428 } 429 if( i>=pParse->nVarExpr ){ 430 pExpr->iTable = ++pParse->nVar; 431 if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){ 432 pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10; 433 pParse->apVarExpr = 434 sqlite3DbReallocOrFree( 435 db, 436 pParse->apVarExpr, 437 pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) 438 ); 439 } 440 if( !db->mallocFailed ){ 441 assert( pParse->apVarExpr!=0 ); 442 pParse->apVarExpr[pParse->nVarExpr++] = pExpr; 443 } 444 } 445 } 446 if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){ 447 sqlite3ErrorMsg(pParse, "too many SQL variables"); 448 } 449 } 450 451 /* 452 ** Recursively delete an expression tree. 453 */ 454 void sqlite3ExprDelete(Expr *p){ 455 if( p==0 ) return; 456 if( p->span.dyn ) sqlite3_free((char*)p->span.z); 457 if( p->token.dyn ) sqlite3_free((char*)p->token.z); 458 sqlite3ExprDelete(p->pLeft); 459 sqlite3ExprDelete(p->pRight); 460 sqlite3ExprListDelete(p->pList); 461 sqlite3SelectDelete(p->pSelect); 462 sqlite3_free(p); 463 } 464 465 /* 466 ** The Expr.token field might be a string literal that is quoted. 467 ** If so, remove the quotation marks. 468 */ 469 void sqlite3DequoteExpr(sqlite3 *db, Expr *p){ 470 if( ExprHasAnyProperty(p, EP_Dequoted) ){ 471 return; 472 } 473 ExprSetProperty(p, EP_Dequoted); 474 if( p->token.dyn==0 ){ 475 sqlite3TokenCopy(db, &p->token, &p->token); 476 } 477 sqlite3Dequote((char*)p->token.z); 478 } 479 480 481 /* 482 ** The following group of routines make deep copies of expressions, 483 ** expression lists, ID lists, and select statements. The copies can 484 ** be deleted (by being passed to their respective ...Delete() routines) 485 ** without effecting the originals. 486 ** 487 ** The expression list, ID, and source lists return by sqlite3ExprListDup(), 488 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 489 ** by subsequent calls to sqlite*ListAppend() routines. 490 ** 491 ** Any tables that the SrcList might point to are not duplicated. 492 */ 493 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){ 494 Expr *pNew; 495 if( p==0 ) return 0; 496 pNew = sqlite3DbMallocRaw(db, sizeof(*p) ); 497 if( pNew==0 ) return 0; 498 memcpy(pNew, p, sizeof(*pNew)); 499 if( p->token.z!=0 ){ 500 pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n); 501 pNew->token.dyn = 1; 502 }else{ 503 assert( pNew->token.z==0 ); 504 } 505 pNew->span.z = 0; 506 pNew->pLeft = sqlite3ExprDup(db, p->pLeft); 507 pNew->pRight = sqlite3ExprDup(db, p->pRight); 508 pNew->pList = sqlite3ExprListDup(db, p->pList); 509 pNew->pSelect = sqlite3SelectDup(db, p->pSelect); 510 return pNew; 511 } 512 void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){ 513 if( pTo->dyn ) sqlite3_free((char*)pTo->z); 514 if( pFrom->z ){ 515 pTo->n = pFrom->n; 516 pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n); 517 pTo->dyn = 1; 518 }else{ 519 pTo->z = 0; 520 } 521 } 522 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){ 523 ExprList *pNew; 524 struct ExprList_item *pItem, *pOldItem; 525 int i; 526 if( p==0 ) return 0; 527 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) ); 528 if( pNew==0 ) return 0; 529 pNew->iECursor = 0; 530 pNew->nExpr = pNew->nAlloc = p->nExpr; 531 pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) ); 532 if( pItem==0 ){ 533 sqlite3_free(pNew); 534 return 0; 535 } 536 pOldItem = p->a; 537 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){ 538 Expr *pNewExpr, *pOldExpr; 539 pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr); 540 if( pOldExpr->span.z!=0 && pNewExpr ){ 541 /* Always make a copy of the span for top-level expressions in the 542 ** expression list. The logic in SELECT processing that determines 543 ** the names of columns in the result set needs this information */ 544 sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span); 545 } 546 assert( pNewExpr==0 || pNewExpr->span.z!=0 547 || pOldExpr->span.z==0 548 || db->mallocFailed ); 549 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 550 pItem->sortOrder = pOldItem->sortOrder; 551 pItem->isAgg = pOldItem->isAgg; 552 pItem->done = 0; 553 } 554 return pNew; 555 } 556 557 /* 558 ** If cursors, triggers, views and subqueries are all omitted from 559 ** the build, then none of the following routines, except for 560 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes 561 ** called with a NULL argument. 562 */ 563 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ 564 || !defined(SQLITE_OMIT_SUBQUERY) 565 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){ 566 SrcList *pNew; 567 int i; 568 int nByte; 569 if( p==0 ) return 0; 570 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); 571 pNew = sqlite3DbMallocRaw(db, nByte ); 572 if( pNew==0 ) return 0; 573 pNew->nSrc = pNew->nAlloc = p->nSrc; 574 for(i=0; i<p->nSrc; i++){ 575 struct SrcList_item *pNewItem = &pNew->a[i]; 576 struct SrcList_item *pOldItem = &p->a[i]; 577 Table *pTab; 578 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); 579 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 580 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); 581 pNewItem->jointype = pOldItem->jointype; 582 pNewItem->iCursor = pOldItem->iCursor; 583 pNewItem->isPopulated = pOldItem->isPopulated; 584 pTab = pNewItem->pTab = pOldItem->pTab; 585 if( pTab ){ 586 pTab->nRef++; 587 } 588 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect); 589 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn); 590 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); 591 pNewItem->colUsed = pOldItem->colUsed; 592 } 593 return pNew; 594 } 595 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ 596 IdList *pNew; 597 int i; 598 if( p==0 ) return 0; 599 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) ); 600 if( pNew==0 ) return 0; 601 pNew->nId = pNew->nAlloc = p->nId; 602 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) ); 603 if( pNew->a==0 ){ 604 sqlite3_free(pNew); 605 return 0; 606 } 607 for(i=0; i<p->nId; i++){ 608 struct IdList_item *pNewItem = &pNew->a[i]; 609 struct IdList_item *pOldItem = &p->a[i]; 610 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 611 pNewItem->idx = pOldItem->idx; 612 } 613 return pNew; 614 } 615 Select *sqlite3SelectDup(sqlite3 *db, Select *p){ 616 Select *pNew; 617 if( p==0 ) return 0; 618 pNew = sqlite3DbMallocRaw(db, sizeof(*p) ); 619 if( pNew==0 ) return 0; 620 pNew->isDistinct = p->isDistinct; 621 pNew->pEList = sqlite3ExprListDup(db, p->pEList); 622 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc); 623 pNew->pWhere = sqlite3ExprDup(db, p->pWhere); 624 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy); 625 pNew->pHaving = sqlite3ExprDup(db, p->pHaving); 626 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy); 627 pNew->op = p->op; 628 pNew->pPrior = sqlite3SelectDup(db, p->pPrior); 629 pNew->pLimit = sqlite3ExprDup(db, p->pLimit); 630 pNew->pOffset = sqlite3ExprDup(db, p->pOffset); 631 pNew->iLimit = -1; 632 pNew->iOffset = -1; 633 pNew->isResolved = p->isResolved; 634 pNew->isAgg = p->isAgg; 635 pNew->usesEphm = 0; 636 pNew->disallowOrderBy = 0; 637 pNew->pRightmost = 0; 638 pNew->addrOpenEphm[0] = -1; 639 pNew->addrOpenEphm[1] = -1; 640 pNew->addrOpenEphm[2] = -1; 641 return pNew; 642 } 643 #else 644 Select *sqlite3SelectDup(sqlite3 *db, Select *p){ 645 assert( p==0 ); 646 return 0; 647 } 648 #endif 649 650 651 /* 652 ** Add a new element to the end of an expression list. If pList is 653 ** initially NULL, then create a new expression list. 654 */ 655 ExprList *sqlite3ExprListAppend( 656 Parse *pParse, /* Parsing context */ 657 ExprList *pList, /* List to which to append. Might be NULL */ 658 Expr *pExpr, /* Expression to be appended */ 659 Token *pName /* AS keyword for the expression */ 660 ){ 661 sqlite3 *db = pParse->db; 662 if( pList==0 ){ 663 pList = sqlite3DbMallocZero(db, sizeof(ExprList) ); 664 if( pList==0 ){ 665 goto no_mem; 666 } 667 assert( pList->nAlloc==0 ); 668 } 669 if( pList->nAlloc<=pList->nExpr ){ 670 struct ExprList_item *a; 671 int n = pList->nAlloc*2 + 4; 672 a = sqlite3_realloc(pList->a, n*sizeof(pList->a[0])); 673 if( a==0 ){ 674 goto no_mem; 675 } 676 pList->a = a; 677 pList->nAlloc = n; 678 } 679 assert( pList->a!=0 ); 680 if( pExpr || pName ){ 681 struct ExprList_item *pItem = &pList->a[pList->nExpr++]; 682 memset(pItem, 0, sizeof(*pItem)); 683 pItem->zName = sqlite3NameFromToken(db, pName); 684 pItem->pExpr = pExpr; 685 } 686 return pList; 687 688 no_mem: 689 /* Avoid leaking memory if malloc has failed. */ 690 db->mallocFailed = 1; 691 sqlite3ExprDelete(pExpr); 692 sqlite3ExprListDelete(pList); 693 return 0; 694 } 695 696 /* 697 ** If the expression list pEList contains more than iLimit elements, 698 ** leave an error message in pParse. 699 */ 700 void sqlite3ExprListCheckLength( 701 Parse *pParse, 702 ExprList *pEList, 703 int iLimit, 704 const char *zObject 705 ){ 706 if( pEList && pEList->nExpr>iLimit ){ 707 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); 708 } 709 } 710 711 712 #if SQLITE_MAX_EXPR_DEPTH>0 713 /* The following three functions, heightOfExpr(), heightOfExprList() 714 ** and heightOfSelect(), are used to determine the maximum height 715 ** of any expression tree referenced by the structure passed as the 716 ** first argument. 717 ** 718 ** If this maximum height is greater than the current value pointed 719 ** to by pnHeight, the second parameter, then set *pnHeight to that 720 ** value. 721 */ 722 static void heightOfExpr(Expr *p, int *pnHeight){ 723 if( p ){ 724 if( p->nHeight>*pnHeight ){ 725 *pnHeight = p->nHeight; 726 } 727 } 728 } 729 static void heightOfExprList(ExprList *p, int *pnHeight){ 730 if( p ){ 731 int i; 732 for(i=0; i<p->nExpr; i++){ 733 heightOfExpr(p->a[i].pExpr, pnHeight); 734 } 735 } 736 } 737 static void heightOfSelect(Select *p, int *pnHeight){ 738 if( p ){ 739 heightOfExpr(p->pWhere, pnHeight); 740 heightOfExpr(p->pHaving, pnHeight); 741 heightOfExpr(p->pLimit, pnHeight); 742 heightOfExpr(p->pOffset, pnHeight); 743 heightOfExprList(p->pEList, pnHeight); 744 heightOfExprList(p->pGroupBy, pnHeight); 745 heightOfExprList(p->pOrderBy, pnHeight); 746 heightOfSelect(p->pPrior, pnHeight); 747 } 748 } 749 750 /* 751 ** Set the Expr.nHeight variable in the structure passed as an 752 ** argument. An expression with no children, Expr.pList or 753 ** Expr.pSelect member has a height of 1. Any other expression 754 ** has a height equal to the maximum height of any other 755 ** referenced Expr plus one. 756 */ 757 void sqlite3ExprSetHeight(Expr *p){ 758 int nHeight = 0; 759 heightOfExpr(p->pLeft, &nHeight); 760 heightOfExpr(p->pRight, &nHeight); 761 heightOfExprList(p->pList, &nHeight); 762 heightOfSelect(p->pSelect, &nHeight); 763 p->nHeight = nHeight + 1; 764 } 765 766 /* 767 ** Return the maximum height of any expression tree referenced 768 ** by the select statement passed as an argument. 769 */ 770 int sqlite3SelectExprHeight(Select *p){ 771 int nHeight = 0; 772 heightOfSelect(p, &nHeight); 773 return nHeight; 774 } 775 #endif 776 777 /* 778 ** Delete an entire expression list. 779 */ 780 void sqlite3ExprListDelete(ExprList *pList){ 781 int i; 782 struct ExprList_item *pItem; 783 if( pList==0 ) return; 784 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) ); 785 assert( pList->nExpr<=pList->nAlloc ); 786 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ 787 sqlite3ExprDelete(pItem->pExpr); 788 sqlite3_free(pItem->zName); 789 } 790 sqlite3_free(pList->a); 791 sqlite3_free(pList); 792 } 793 794 /* 795 ** Walk an expression tree. Call xFunc for each node visited. 796 ** 797 ** The return value from xFunc determines whether the tree walk continues. 798 ** 0 means continue walking the tree. 1 means do not walk children 799 ** of the current node but continue with siblings. 2 means abandon 800 ** the tree walk completely. 801 ** 802 ** The return value from this routine is 1 to abandon the tree walk 803 ** and 0 to continue. 804 ** 805 ** NOTICE: This routine does *not* descend into subqueries. 806 */ 807 static int walkExprList(ExprList *, int (*)(void *, Expr*), void *); 808 static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){ 809 int rc; 810 if( pExpr==0 ) return 0; 811 rc = (*xFunc)(pArg, pExpr); 812 if( rc==0 ){ 813 if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1; 814 if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1; 815 if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1; 816 } 817 return rc>1; 818 } 819 820 /* 821 ** Call walkExprTree() for every expression in list p. 822 */ 823 static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){ 824 int i; 825 struct ExprList_item *pItem; 826 if( !p ) return 0; 827 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){ 828 if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1; 829 } 830 return 0; 831 } 832 833 /* 834 ** Call walkExprTree() for every expression in Select p, not including 835 ** expressions that are part of sub-selects in any FROM clause or the LIMIT 836 ** or OFFSET expressions.. 837 */ 838 static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){ 839 walkExprList(p->pEList, xFunc, pArg); 840 walkExprTree(p->pWhere, xFunc, pArg); 841 walkExprList(p->pGroupBy, xFunc, pArg); 842 walkExprTree(p->pHaving, xFunc, pArg); 843 walkExprList(p->pOrderBy, xFunc, pArg); 844 if( p->pPrior ){ 845 walkSelectExpr(p->pPrior, xFunc, pArg); 846 } 847 return 0; 848 } 849 850 851 /* 852 ** This routine is designed as an xFunc for walkExprTree(). 853 ** 854 ** pArg is really a pointer to an integer. If we can tell by looking 855 ** at pExpr that the expression that contains pExpr is not a constant 856 ** expression, then set *pArg to 0 and return 2 to abandon the tree walk. 857 ** If pExpr does does not disqualify the expression from being a constant 858 ** then do nothing. 859 ** 860 ** After walking the whole tree, if no nodes are found that disqualify 861 ** the expression as constant, then we assume the whole expression 862 ** is constant. See sqlite3ExprIsConstant() for additional information. 863 */ 864 static int exprNodeIsConstant(void *pArg, Expr *pExpr){ 865 int *pN = (int*)pArg; 866 867 /* If *pArg is 3 then any term of the expression that comes from 868 ** the ON or USING clauses of a join disqualifies the expression 869 ** from being considered constant. */ 870 if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){ 871 *pN = 0; 872 return 2; 873 } 874 875 switch( pExpr->op ){ 876 /* Consider functions to be constant if all their arguments are constant 877 ** and *pArg==2 */ 878 case TK_FUNCTION: 879 if( (*pN)==2 ) return 0; 880 /* Fall through */ 881 case TK_ID: 882 case TK_COLUMN: 883 case TK_DOT: 884 case TK_AGG_FUNCTION: 885 case TK_AGG_COLUMN: 886 #ifndef SQLITE_OMIT_SUBQUERY 887 case TK_SELECT: 888 case TK_EXISTS: 889 #endif 890 *pN = 0; 891 return 2; 892 case TK_IN: 893 if( pExpr->pSelect ){ 894 *pN = 0; 895 return 2; 896 } 897 default: 898 return 0; 899 } 900 } 901 902 /* 903 ** Walk an expression tree. Return 1 if the expression is constant 904 ** and 0 if it involves variables or function calls. 905 ** 906 ** For the purposes of this function, a double-quoted string (ex: "abc") 907 ** is considered a variable but a single-quoted string (ex: 'abc') is 908 ** a constant. 909 */ 910 int sqlite3ExprIsConstant(Expr *p){ 911 int isConst = 1; 912 walkExprTree(p, exprNodeIsConstant, &isConst); 913 return isConst; 914 } 915 916 /* 917 ** Walk an expression tree. Return 1 if the expression is constant 918 ** that does no originate from the ON or USING clauses of a join. 919 ** Return 0 if it involves variables or function calls or terms from 920 ** an ON or USING clause. 921 */ 922 int sqlite3ExprIsConstantNotJoin(Expr *p){ 923 int isConst = 3; 924 walkExprTree(p, exprNodeIsConstant, &isConst); 925 return isConst!=0; 926 } 927 928 /* 929 ** Walk an expression tree. Return 1 if the expression is constant 930 ** or a function call with constant arguments. Return and 0 if there 931 ** are any variables. 932 ** 933 ** For the purposes of this function, a double-quoted string (ex: "abc") 934 ** is considered a variable but a single-quoted string (ex: 'abc') is 935 ** a constant. 936 */ 937 int sqlite3ExprIsConstantOrFunction(Expr *p){ 938 int isConst = 2; 939 walkExprTree(p, exprNodeIsConstant, &isConst); 940 return isConst!=0; 941 } 942 943 /* 944 ** If the expression p codes a constant integer that is small enough 945 ** to fit in a 32-bit integer, return 1 and put the value of the integer 946 ** in *pValue. If the expression is not an integer or if it is too big 947 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. 948 */ 949 int sqlite3ExprIsInteger(Expr *p, int *pValue){ 950 switch( p->op ){ 951 case TK_INTEGER: { 952 if( sqlite3GetInt32((char*)p->token.z, pValue) ){ 953 return 1; 954 } 955 break; 956 } 957 case TK_UPLUS: { 958 return sqlite3ExprIsInteger(p->pLeft, pValue); 959 } 960 case TK_UMINUS: { 961 int v; 962 if( sqlite3ExprIsInteger(p->pLeft, &v) ){ 963 *pValue = -v; 964 return 1; 965 } 966 break; 967 } 968 default: break; 969 } 970 return 0; 971 } 972 973 /* 974 ** Return TRUE if the given string is a row-id column name. 975 */ 976 int sqlite3IsRowid(const char *z){ 977 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; 978 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; 979 if( sqlite3StrICmp(z, "OID")==0 ) return 1; 980 return 0; 981 } 982 983 /* 984 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up 985 ** that name in the set of source tables in pSrcList and make the pExpr 986 ** expression node refer back to that source column. The following changes 987 ** are made to pExpr: 988 ** 989 ** pExpr->iDb Set the index in db->aDb[] of the database holding 990 ** the table. 991 ** pExpr->iTable Set to the cursor number for the table obtained 992 ** from pSrcList. 993 ** pExpr->iColumn Set to the column number within the table. 994 ** pExpr->op Set to TK_COLUMN. 995 ** pExpr->pLeft Any expression this points to is deleted 996 ** pExpr->pRight Any expression this points to is deleted. 997 ** 998 ** The pDbToken is the name of the database (the "X"). This value may be 999 ** NULL meaning that name is of the form Y.Z or Z. Any available database 1000 ** can be used. The pTableToken is the name of the table (the "Y"). This 1001 ** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it 1002 ** means that the form of the name is Z and that columns from any table 1003 ** can be used. 1004 ** 1005 ** If the name cannot be resolved unambiguously, leave an error message 1006 ** in pParse and return non-zero. Return zero on success. 1007 */ 1008 static int lookupName( 1009 Parse *pParse, /* The parsing context */ 1010 Token *pDbToken, /* Name of the database containing table, or NULL */ 1011 Token *pTableToken, /* Name of table containing column, or NULL */ 1012 Token *pColumnToken, /* Name of the column. */ 1013 NameContext *pNC, /* The name context used to resolve the name */ 1014 Expr *pExpr /* Make this EXPR node point to the selected column */ 1015 ){ 1016 char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */ 1017 char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */ 1018 char *zCol = 0; /* Name of the column. The "Z" */ 1019 int i, j; /* Loop counters */ 1020 int cnt = 0; /* Number of matching column names */ 1021 int cntTab = 0; /* Number of matching table names */ 1022 sqlite3 *db = pParse->db; /* The database */ 1023 struct SrcList_item *pItem; /* Use for looping over pSrcList items */ 1024 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ 1025 NameContext *pTopNC = pNC; /* First namecontext in the list */ 1026 1027 assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */ 1028 zDb = sqlite3NameFromToken(db, pDbToken); 1029 zTab = sqlite3NameFromToken(db, pTableToken); 1030 zCol = sqlite3NameFromToken(db, pColumnToken); 1031 if( db->mallocFailed ){ 1032 goto lookupname_end; 1033 } 1034 1035 pExpr->iTable = -1; 1036 while( pNC && cnt==0 ){ 1037 ExprList *pEList; 1038 SrcList *pSrcList = pNC->pSrcList; 1039 1040 if( pSrcList ){ 1041 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ 1042 Table *pTab; 1043 int iDb; 1044 Column *pCol; 1045 1046 pTab = pItem->pTab; 1047 assert( pTab!=0 ); 1048 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1049 assert( pTab->nCol>0 ); 1050 if( zTab ){ 1051 if( pItem->zAlias ){ 1052 char *zTabName = pItem->zAlias; 1053 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue; 1054 }else{ 1055 char *zTabName = pTab->zName; 1056 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue; 1057 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){ 1058 continue; 1059 } 1060 } 1061 } 1062 if( 0==(cntTab++) ){ 1063 pExpr->iTable = pItem->iCursor; 1064 pExpr->pSchema = pTab->pSchema; 1065 pMatch = pItem; 1066 } 1067 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ 1068 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ 1069 const char *zColl = pTab->aCol[j].zColl; 1070 IdList *pUsing; 1071 cnt++; 1072 pExpr->iTable = pItem->iCursor; 1073 pMatch = pItem; 1074 pExpr->pSchema = pTab->pSchema; 1075 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ 1076 pExpr->iColumn = j==pTab->iPKey ? -1 : j; 1077 pExpr->affinity = pTab->aCol[j].affinity; 1078 if( (pExpr->flags & EP_ExpCollate)==0 ){ 1079 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0); 1080 } 1081 if( i<pSrcList->nSrc-1 ){ 1082 if( pItem[1].jointype & JT_NATURAL ){ 1083 /* If this match occurred in the left table of a natural join, 1084 ** then skip the right table to avoid a duplicate match */ 1085 pItem++; 1086 i++; 1087 }else if( (pUsing = pItem[1].pUsing)!=0 ){ 1088 /* If this match occurs on a column that is in the USING clause 1089 ** of a join, skip the search of the right table of the join 1090 ** to avoid a duplicate match there. */ 1091 int k; 1092 for(k=0; k<pUsing->nId; k++){ 1093 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){ 1094 pItem++; 1095 i++; 1096 break; 1097 } 1098 } 1099 } 1100 } 1101 break; 1102 } 1103 } 1104 } 1105 } 1106 1107 #ifndef SQLITE_OMIT_TRIGGER 1108 /* If we have not already resolved the name, then maybe 1109 ** it is a new.* or old.* trigger argument reference 1110 */ 1111 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){ 1112 TriggerStack *pTriggerStack = pParse->trigStack; 1113 Table *pTab = 0; 1114 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){ 1115 pExpr->iTable = pTriggerStack->newIdx; 1116 assert( pTriggerStack->pTab ); 1117 pTab = pTriggerStack->pTab; 1118 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){ 1119 pExpr->iTable = pTriggerStack->oldIdx; 1120 assert( pTriggerStack->pTab ); 1121 pTab = pTriggerStack->pTab; 1122 } 1123 1124 if( pTab ){ 1125 int iCol; 1126 Column *pCol = pTab->aCol; 1127 1128 pExpr->pSchema = pTab->pSchema; 1129 cntTab++; 1130 for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) { 1131 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ 1132 const char *zColl = pTab->aCol[iCol].zColl; 1133 cnt++; 1134 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol; 1135 pExpr->affinity = pTab->aCol[iCol].affinity; 1136 if( (pExpr->flags & EP_ExpCollate)==0 ){ 1137 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0); 1138 } 1139 pExpr->pTab = pTab; 1140 break; 1141 } 1142 } 1143 } 1144 } 1145 #endif /* !defined(SQLITE_OMIT_TRIGGER) */ 1146 1147 /* 1148 ** Perhaps the name is a reference to the ROWID 1149 */ 1150 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){ 1151 cnt = 1; 1152 pExpr->iColumn = -1; 1153 pExpr->affinity = SQLITE_AFF_INTEGER; 1154 } 1155 1156 /* 1157 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z 1158 ** might refer to an result-set alias. This happens, for example, when 1159 ** we are resolving names in the WHERE clause of the following command: 1160 ** 1161 ** SELECT a+b AS x FROM table WHERE x<10; 1162 ** 1163 ** In cases like this, replace pExpr with a copy of the expression that 1164 ** forms the result set entry ("a+b" in the example) and return immediately. 1165 ** Note that the expression in the result set should have already been 1166 ** resolved by the time the WHERE clause is resolved. 1167 */ 1168 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){ 1169 for(j=0; j<pEList->nExpr; j++){ 1170 char *zAs = pEList->a[j].zName; 1171 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 1172 Expr *pDup, *pOrig; 1173 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 1174 assert( pExpr->pList==0 ); 1175 assert( pExpr->pSelect==0 ); 1176 pOrig = pEList->a[j].pExpr; 1177 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){ 1178 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); 1179 sqlite3_free(zCol); 1180 return 2; 1181 } 1182 pDup = sqlite3ExprDup(db, pOrig); 1183 if( pExpr->flags & EP_ExpCollate ){ 1184 pDup->pColl = pExpr->pColl; 1185 pDup->flags |= EP_ExpCollate; 1186 } 1187 if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z); 1188 if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z); 1189 memcpy(pExpr, pDup, sizeof(*pExpr)); 1190 sqlite3_free(pDup); 1191 cnt = 1; 1192 pMatch = 0; 1193 assert( zTab==0 && zDb==0 ); 1194 goto lookupname_end_2; 1195 } 1196 } 1197 } 1198 1199 /* Advance to the next name context. The loop will exit when either 1200 ** we have a match (cnt>0) or when we run out of name contexts. 1201 */ 1202 if( cnt==0 ){ 1203 pNC = pNC->pNext; 1204 } 1205 } 1206 1207 /* 1208 ** If X and Y are NULL (in other words if only the column name Z is 1209 ** supplied) and the value of Z is enclosed in double-quotes, then 1210 ** Z is a string literal if it doesn't match any column names. In that 1211 ** case, we need to return right away and not make any changes to 1212 ** pExpr. 1213 ** 1214 ** Because no reference was made to outer contexts, the pNC->nRef 1215 ** fields are not changed in any context. 1216 */ 1217 if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){ 1218 sqlite3_free(zCol); 1219 return 0; 1220 } 1221 1222 /* 1223 ** cnt==0 means there was not match. cnt>1 means there were two or 1224 ** more matches. Either way, we have an error. 1225 */ 1226 if( cnt!=1 ){ 1227 char *z = 0; 1228 char *zErr; 1229 zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s"; 1230 if( zDb ){ 1231 sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0); 1232 }else if( zTab ){ 1233 sqlite3SetString(&z, zTab, ".", zCol, (char*)0); 1234 }else{ 1235 z = sqlite3StrDup(zCol); 1236 } 1237 sqlite3ErrorMsg(pParse, zErr, z); 1238 sqlite3_free(z); 1239 pTopNC->nErr++; 1240 } 1241 1242 /* If a column from a table in pSrcList is referenced, then record 1243 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes 1244 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the 1245 ** column number is greater than the number of bits in the bitmask 1246 ** then set the high-order bit of the bitmask. 1247 */ 1248 if( pExpr->iColumn>=0 && pMatch!=0 ){ 1249 int n = pExpr->iColumn; 1250 if( n>=sizeof(Bitmask)*8 ){ 1251 n = sizeof(Bitmask)*8-1; 1252 } 1253 assert( pMatch->iCursor==pExpr->iTable ); 1254 pMatch->colUsed |= ((Bitmask)1)<<n; 1255 } 1256 1257 lookupname_end: 1258 /* Clean up and return 1259 */ 1260 sqlite3_free(zDb); 1261 sqlite3_free(zTab); 1262 sqlite3ExprDelete(pExpr->pLeft); 1263 pExpr->pLeft = 0; 1264 sqlite3ExprDelete(pExpr->pRight); 1265 pExpr->pRight = 0; 1266 pExpr->op = TK_COLUMN; 1267 lookupname_end_2: 1268 sqlite3_free(zCol); 1269 if( cnt==1 ){ 1270 assert( pNC!=0 ); 1271 sqlite3AuthRead(pParse, pExpr, pNC->pSrcList); 1272 if( pMatch && !pMatch->pSelect ){ 1273 pExpr->pTab = pMatch->pTab; 1274 } 1275 /* Increment the nRef value on all name contexts from TopNC up to 1276 ** the point where the name matched. */ 1277 for(;;){ 1278 assert( pTopNC!=0 ); 1279 pTopNC->nRef++; 1280 if( pTopNC==pNC ) break; 1281 pTopNC = pTopNC->pNext; 1282 } 1283 return 0; 1284 } else { 1285 return 1; 1286 } 1287 } 1288 1289 /* 1290 ** This routine is designed as an xFunc for walkExprTree(). 1291 ** 1292 ** Resolve symbolic names into TK_COLUMN operators for the current 1293 ** node in the expression tree. Return 0 to continue the search down 1294 ** the tree or 2 to abort the tree walk. 1295 ** 1296 ** This routine also does error checking and name resolution for 1297 ** function names. The operator for aggregate functions is changed 1298 ** to TK_AGG_FUNCTION. 1299 */ 1300 static int nameResolverStep(void *pArg, Expr *pExpr){ 1301 NameContext *pNC = (NameContext*)pArg; 1302 Parse *pParse; 1303 1304 if( pExpr==0 ) return 1; 1305 assert( pNC!=0 ); 1306 pParse = pNC->pParse; 1307 1308 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1; 1309 ExprSetProperty(pExpr, EP_Resolved); 1310 #ifndef NDEBUG 1311 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ 1312 SrcList *pSrcList = pNC->pSrcList; 1313 int i; 1314 for(i=0; i<pNC->pSrcList->nSrc; i++){ 1315 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab); 1316 } 1317 } 1318 #endif 1319 switch( pExpr->op ){ 1320 /* Double-quoted strings (ex: "abc") are used as identifiers if 1321 ** possible. Otherwise they remain as strings. Single-quoted 1322 ** strings (ex: 'abc') are always string literals. 1323 */ 1324 case TK_STRING: { 1325 if( pExpr->token.z[0]=='\'' ) break; 1326 /* Fall thru into the TK_ID case if this is a double-quoted string */ 1327 } 1328 /* A lone identifier is the name of a column. 1329 */ 1330 case TK_ID: { 1331 lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr); 1332 return 1; 1333 } 1334 1335 /* A table name and column name: ID.ID 1336 ** Or a database, table and column: ID.ID.ID 1337 */ 1338 case TK_DOT: { 1339 Token *pColumn; 1340 Token *pTable; 1341 Token *pDb; 1342 Expr *pRight; 1343 1344 /* if( pSrcList==0 ) break; */ 1345 pRight = pExpr->pRight; 1346 if( pRight->op==TK_ID ){ 1347 pDb = 0; 1348 pTable = &pExpr->pLeft->token; 1349 pColumn = &pRight->token; 1350 }else{ 1351 assert( pRight->op==TK_DOT ); 1352 pDb = &pExpr->pLeft->token; 1353 pTable = &pRight->pLeft->token; 1354 pColumn = &pRight->pRight->token; 1355 } 1356 lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr); 1357 return 1; 1358 } 1359 1360 /* Resolve function names 1361 */ 1362 case TK_CONST_FUNC: 1363 case TK_FUNCTION: { 1364 ExprList *pList = pExpr->pList; /* The argument list */ 1365 int n = pList ? pList->nExpr : 0; /* Number of arguments */ 1366 int no_such_func = 0; /* True if no such function exists */ 1367 int wrong_num_args = 0; /* True if wrong number of arguments */ 1368 int is_agg = 0; /* True if is an aggregate function */ 1369 int i; 1370 int auth; /* Authorization to use the function */ 1371 int nId; /* Number of characters in function name */ 1372 const char *zId; /* The function name. */ 1373 FuncDef *pDef; /* Information about the function */ 1374 int enc = ENC(pParse->db); /* The database encoding */ 1375 1376 zId = (char*)pExpr->token.z; 1377 nId = pExpr->token.n; 1378 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0); 1379 if( pDef==0 ){ 1380 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0); 1381 if( pDef==0 ){ 1382 no_such_func = 1; 1383 }else{ 1384 wrong_num_args = 1; 1385 } 1386 }else{ 1387 is_agg = pDef->xFunc==0; 1388 } 1389 #ifndef SQLITE_OMIT_AUTHORIZATION 1390 if( pDef ){ 1391 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0); 1392 if( auth!=SQLITE_OK ){ 1393 if( auth==SQLITE_DENY ){ 1394 sqlite3ErrorMsg(pParse, "not authorized to use function: %s", 1395 pDef->zName); 1396 pNC->nErr++; 1397 } 1398 pExpr->op = TK_NULL; 1399 return 1; 1400 } 1401 } 1402 #endif 1403 if( is_agg && !pNC->allowAgg ){ 1404 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId); 1405 pNC->nErr++; 1406 is_agg = 0; 1407 }else if( no_such_func ){ 1408 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); 1409 pNC->nErr++; 1410 }else if( wrong_num_args ){ 1411 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", 1412 nId, zId); 1413 pNC->nErr++; 1414 } 1415 if( is_agg ){ 1416 pExpr->op = TK_AGG_FUNCTION; 1417 pNC->hasAgg = 1; 1418 } 1419 if( is_agg ) pNC->allowAgg = 0; 1420 for(i=0; pNC->nErr==0 && i<n; i++){ 1421 walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC); 1422 } 1423 if( is_agg ) pNC->allowAgg = 1; 1424 /* FIX ME: Compute pExpr->affinity based on the expected return 1425 ** type of the function 1426 */ 1427 return is_agg; 1428 } 1429 #ifndef SQLITE_OMIT_SUBQUERY 1430 case TK_SELECT: 1431 case TK_EXISTS: 1432 #endif 1433 case TK_IN: { 1434 if( pExpr->pSelect ){ 1435 int nRef = pNC->nRef; 1436 #ifndef SQLITE_OMIT_CHECK 1437 if( pNC->isCheck ){ 1438 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints"); 1439 } 1440 #endif 1441 sqlite3SelectResolve(pParse, pExpr->pSelect, pNC); 1442 assert( pNC->nRef>=nRef ); 1443 if( nRef!=pNC->nRef ){ 1444 ExprSetProperty(pExpr, EP_VarSelect); 1445 } 1446 } 1447 break; 1448 } 1449 #ifndef SQLITE_OMIT_CHECK 1450 case TK_VARIABLE: { 1451 if( pNC->isCheck ){ 1452 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints"); 1453 } 1454 break; 1455 } 1456 #endif 1457 } 1458 return 0; 1459 } 1460 1461 /* 1462 ** This routine walks an expression tree and resolves references to 1463 ** table columns. Nodes of the form ID.ID or ID resolve into an 1464 ** index to the table in the table list and a column offset. The 1465 ** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable 1466 ** value is changed to the index of the referenced table in pTabList 1467 ** plus the "base" value. The base value will ultimately become the 1468 ** VDBE cursor number for a cursor that is pointing into the referenced 1469 ** table. The Expr.iColumn value is changed to the index of the column 1470 ** of the referenced table. The Expr.iColumn value for the special 1471 ** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an 1472 ** alias for ROWID. 1473 ** 1474 ** Also resolve function names and check the functions for proper 1475 ** usage. Make sure all function names are recognized and all functions 1476 ** have the correct number of arguments. Leave an error message 1477 ** in pParse->zErrMsg if anything is amiss. Return the number of errors. 1478 ** 1479 ** If the expression contains aggregate functions then set the EP_Agg 1480 ** property on the expression. 1481 */ 1482 int sqlite3ExprResolveNames( 1483 NameContext *pNC, /* Namespace to resolve expressions in. */ 1484 Expr *pExpr /* The expression to be analyzed. */ 1485 ){ 1486 int savedHasAgg; 1487 if( pExpr==0 ) return 0; 1488 #if SQLITE_MAX_EXPR_DEPTH>0 1489 if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){ 1490 sqlite3ErrorMsg(pNC->pParse, 1491 "Expression tree is too large (maximum depth %d)", 1492 SQLITE_MAX_EXPR_DEPTH 1493 ); 1494 return 1; 1495 } 1496 pNC->pParse->nHeight += pExpr->nHeight; 1497 #endif 1498 savedHasAgg = pNC->hasAgg; 1499 pNC->hasAgg = 0; 1500 walkExprTree(pExpr, nameResolverStep, pNC); 1501 #if SQLITE_MAX_EXPR_DEPTH>0 1502 pNC->pParse->nHeight -= pExpr->nHeight; 1503 #endif 1504 if( pNC->nErr>0 ){ 1505 ExprSetProperty(pExpr, EP_Error); 1506 } 1507 if( pNC->hasAgg ){ 1508 ExprSetProperty(pExpr, EP_Agg); 1509 }else if( savedHasAgg ){ 1510 pNC->hasAgg = 1; 1511 } 1512 return ExprHasProperty(pExpr, EP_Error); 1513 } 1514 1515 /* 1516 ** A pointer instance of this structure is used to pass information 1517 ** through walkExprTree into codeSubqueryStep(). 1518 */ 1519 typedef struct QueryCoder QueryCoder; 1520 struct QueryCoder { 1521 Parse *pParse; /* The parsing context */ 1522 NameContext *pNC; /* Namespace of first enclosing query */ 1523 }; 1524 1525 1526 /* 1527 ** Generate code for scalar subqueries used as an expression 1528 ** and IN operators. Examples: 1529 ** 1530 ** (SELECT a FROM b) -- subquery 1531 ** EXISTS (SELECT a FROM b) -- EXISTS subquery 1532 ** x IN (4,5,11) -- IN operator with list on right-hand side 1533 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right 1534 ** 1535 ** The pExpr parameter describes the expression that contains the IN 1536 ** operator or subquery. 1537 */ 1538 #ifndef SQLITE_OMIT_SUBQUERY 1539 void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ 1540 int testAddr = 0; /* One-time test address */ 1541 Vdbe *v = sqlite3GetVdbe(pParse); 1542 if( v==0 ) return; 1543 1544 1545 /* This code must be run in its entirety every time it is encountered 1546 ** if any of the following is true: 1547 ** 1548 ** * The right-hand side is a correlated subquery 1549 ** * The right-hand side is an expression list containing variables 1550 ** * We are inside a trigger 1551 ** 1552 ** If all of the above are false, then we can run this code just once 1553 ** save the results, and reuse the same result on subsequent invocations. 1554 */ 1555 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){ 1556 int mem = pParse->nMem++; 1557 sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0); 1558 testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0); 1559 assert( testAddr>0 || pParse->db->mallocFailed ); 1560 sqlite3VdbeAddOp(v, OP_MemInt, 1, mem); 1561 } 1562 1563 switch( pExpr->op ){ 1564 case TK_IN: { 1565 char affinity; 1566 KeyInfo keyInfo; 1567 int addr; /* Address of OP_OpenEphemeral instruction */ 1568 1569 affinity = sqlite3ExprAffinity(pExpr->pLeft); 1570 1571 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)' 1572 ** expression it is handled the same way. A virtual table is 1573 ** filled with single-field index keys representing the results 1574 ** from the SELECT or the <exprlist>. 1575 ** 1576 ** If the 'x' expression is a column value, or the SELECT... 1577 ** statement returns a column value, then the affinity of that 1578 ** column is used to build the index keys. If both 'x' and the 1579 ** SELECT... statement are columns, then numeric affinity is used 1580 ** if either column has NUMERIC or INTEGER affinity. If neither 1581 ** 'x' nor the SELECT... statement are columns, then numeric affinity 1582 ** is used. 1583 */ 1584 pExpr->iTable = pParse->nTab++; 1585 addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0); 1586 memset(&keyInfo, 0, sizeof(keyInfo)); 1587 keyInfo.nField = 1; 1588 sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1); 1589 1590 if( pExpr->pSelect ){ 1591 /* Case 1: expr IN (SELECT ...) 1592 ** 1593 ** Generate code to write the results of the select into the temporary 1594 ** table allocated and opened above. 1595 */ 1596 int iParm = pExpr->iTable + (((int)affinity)<<16); 1597 ExprList *pEList; 1598 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); 1599 if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){ 1600 return; 1601 } 1602 pEList = pExpr->pSelect->pEList; 1603 if( pEList && pEList->nExpr>0 ){ 1604 keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, 1605 pEList->a[0].pExpr); 1606 } 1607 }else if( pExpr->pList ){ 1608 /* Case 2: expr IN (exprlist) 1609 ** 1610 ** For each expression, build an index key from the evaluation and 1611 ** store it in the temporary table. If <expr> is a column, then use 1612 ** that columns affinity when building index keys. If <expr> is not 1613 ** a column, use numeric affinity. 1614 */ 1615 int i; 1616 ExprList *pList = pExpr->pList; 1617 struct ExprList_item *pItem; 1618 1619 if( !affinity ){ 1620 affinity = SQLITE_AFF_NONE; 1621 } 1622 keyInfo.aColl[0] = pExpr->pLeft->pColl; 1623 1624 /* Loop through each expression in <exprlist>. */ 1625 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ 1626 Expr *pE2 = pItem->pExpr; 1627 1628 /* If the expression is not constant then we will need to 1629 ** disable the test that was generated above that makes sure 1630 ** this code only executes once. Because for a non-constant 1631 ** expression we need to rerun this code each time. 1632 */ 1633 if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){ 1634 sqlite3VdbeChangeToNoop(v, testAddr-1, 3); 1635 testAddr = 0; 1636 } 1637 1638 /* Evaluate the expression and insert it into the temp table */ 1639 sqlite3ExprCode(pParse, pE2); 1640 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); 1641 sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0); 1642 } 1643 } 1644 sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO); 1645 break; 1646 } 1647 1648 case TK_EXISTS: 1649 case TK_SELECT: { 1650 /* This has to be a scalar SELECT. Generate code to put the 1651 ** value of this select in a memory cell and record the number 1652 ** of the memory cell in iColumn. 1653 */ 1654 static const Token one = { (u8*)"1", 0, 1 }; 1655 Select *pSel; 1656 int iMem; 1657 int sop; 1658 1659 pExpr->iColumn = iMem = pParse->nMem++; 1660 pSel = pExpr->pSelect; 1661 if( pExpr->op==TK_SELECT ){ 1662 sop = SRT_Mem; 1663 sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0); 1664 VdbeComment((v, "# Init subquery result")); 1665 }else{ 1666 sop = SRT_Exists; 1667 sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem); 1668 VdbeComment((v, "# Init EXISTS result")); 1669 } 1670 sqlite3ExprDelete(pSel->pLimit); 1671 pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one); 1672 if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){ 1673 return; 1674 } 1675 break; 1676 } 1677 } 1678 1679 if( testAddr ){ 1680 sqlite3VdbeJumpHere(v, testAddr); 1681 } 1682 1683 return; 1684 } 1685 #endif /* SQLITE_OMIT_SUBQUERY */ 1686 1687 /* 1688 ** Generate an instruction that will put the integer describe by 1689 ** text z[0..n-1] on the stack. 1690 */ 1691 static void codeInteger(Vdbe *v, const char *z, int n){ 1692 assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed ); 1693 if( z ){ 1694 int i; 1695 if( sqlite3GetInt32(z, &i) ){ 1696 sqlite3VdbeAddOp(v, OP_Integer, i, 0); 1697 }else if( sqlite3FitsIn64Bits(z) ){ 1698 sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n); 1699 }else{ 1700 sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n); 1701 } 1702 } 1703 } 1704 1705 1706 /* 1707 ** Generate code that will extract the iColumn-th column from 1708 ** table pTab and push that column value on the stack. There 1709 ** is an open cursor to pTab in iTable. If iColumn<0 then 1710 ** code is generated that extracts the rowid. 1711 */ 1712 void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){ 1713 if( iColumn<0 ){ 1714 int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid; 1715 sqlite3VdbeAddOp(v, op, iTable, 0); 1716 }else if( pTab==0 ){ 1717 sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn); 1718 }else{ 1719 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; 1720 sqlite3VdbeAddOp(v, op, iTable, iColumn); 1721 sqlite3ColumnDefault(v, pTab, iColumn); 1722 #ifndef SQLITE_OMIT_FLOATING_POINT 1723 if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){ 1724 sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0); 1725 } 1726 #endif 1727 } 1728 } 1729 1730 /* 1731 ** Generate code into the current Vdbe to evaluate the given 1732 ** expression and leave the result on the top of stack. 1733 ** 1734 ** This code depends on the fact that certain token values (ex: TK_EQ) 1735 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding 1736 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in 1737 ** the make process cause these values to align. Assert()s in the code 1738 ** below verify that the numbers are aligned correctly. 1739 */ 1740 void sqlite3ExprCode(Parse *pParse, Expr *pExpr){ 1741 Vdbe *v = pParse->pVdbe; 1742 int op; 1743 int stackChng = 1; /* Amount of change to stack depth */ 1744 1745 if( v==0 ) return; 1746 if( pExpr==0 ){ 1747 sqlite3VdbeAddOp(v, OP_Null, 0, 0); 1748 return; 1749 } 1750 op = pExpr->op; 1751 switch( op ){ 1752 case TK_AGG_COLUMN: { 1753 AggInfo *pAggInfo = pExpr->pAggInfo; 1754 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; 1755 if( !pAggInfo->directMode ){ 1756 sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0); 1757 break; 1758 }else if( pAggInfo->useSortingIdx ){ 1759 sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx, 1760 pCol->iSorterColumn); 1761 break; 1762 } 1763 /* Otherwise, fall thru into the TK_COLUMN case */ 1764 } 1765 case TK_COLUMN: { 1766 if( pExpr->iTable<0 ){ 1767 /* This only happens when coding check constraints */ 1768 assert( pParse->ckOffset>0 ); 1769 sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1); 1770 }else{ 1771 sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable); 1772 } 1773 break; 1774 } 1775 case TK_INTEGER: { 1776 codeInteger(v, (char*)pExpr->token.z, pExpr->token.n); 1777 break; 1778 } 1779 case TK_FLOAT: 1780 case TK_STRING: { 1781 assert( TK_FLOAT==OP_Real ); 1782 assert( TK_STRING==OP_String8 ); 1783 sqlite3DequoteExpr(pParse->db, pExpr); 1784 sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n); 1785 break; 1786 } 1787 case TK_NULL: { 1788 sqlite3VdbeAddOp(v, OP_Null, 0, 0); 1789 break; 1790 } 1791 #ifndef SQLITE_OMIT_BLOB_LITERAL 1792 case TK_BLOB: { 1793 int n; 1794 const char *z; 1795 assert( TK_BLOB==OP_HexBlob ); 1796 n = pExpr->token.n - 3; 1797 z = (char*)pExpr->token.z + 2; 1798 assert( n>=0 ); 1799 if( n==0 ){ 1800 z = ""; 1801 } 1802 sqlite3VdbeOp3(v, op, 0, 0, z, n); 1803 break; 1804 } 1805 #endif 1806 case TK_VARIABLE: { 1807 sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0); 1808 if( pExpr->token.n>1 ){ 1809 sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n); 1810 } 1811 break; 1812 } 1813 case TK_REGISTER: { 1814 sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0); 1815 break; 1816 } 1817 #ifndef SQLITE_OMIT_CAST 1818 case TK_CAST: { 1819 /* Expressions of the form: CAST(pLeft AS token) */ 1820 int aff, to_op; 1821 sqlite3ExprCode(pParse, pExpr->pLeft); 1822 aff = sqlite3AffinityType(&pExpr->token); 1823 to_op = aff - SQLITE_AFF_TEXT + OP_ToText; 1824 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT ); 1825 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE ); 1826 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC ); 1827 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER ); 1828 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL ); 1829 sqlite3VdbeAddOp(v, to_op, 0, 0); 1830 stackChng = 0; 1831 break; 1832 } 1833 #endif /* SQLITE_OMIT_CAST */ 1834 case TK_LT: 1835 case TK_LE: 1836 case TK_GT: 1837 case TK_GE: 1838 case TK_NE: 1839 case TK_EQ: { 1840 assert( TK_LT==OP_Lt ); 1841 assert( TK_LE==OP_Le ); 1842 assert( TK_GT==OP_Gt ); 1843 assert( TK_GE==OP_Ge ); 1844 assert( TK_EQ==OP_Eq ); 1845 assert( TK_NE==OP_Ne ); 1846 sqlite3ExprCode(pParse, pExpr->pLeft); 1847 sqlite3ExprCode(pParse, pExpr->pRight); 1848 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0); 1849 stackChng = -1; 1850 break; 1851 } 1852 case TK_AND: 1853 case TK_OR: 1854 case TK_PLUS: 1855 case TK_STAR: 1856 case TK_MINUS: 1857 case TK_REM: 1858 case TK_BITAND: 1859 case TK_BITOR: 1860 case TK_SLASH: 1861 case TK_LSHIFT: 1862 case TK_RSHIFT: 1863 case TK_CONCAT: { 1864 assert( TK_AND==OP_And ); 1865 assert( TK_OR==OP_Or ); 1866 assert( TK_PLUS==OP_Add ); 1867 assert( TK_MINUS==OP_Subtract ); 1868 assert( TK_REM==OP_Remainder ); 1869 assert( TK_BITAND==OP_BitAnd ); 1870 assert( TK_BITOR==OP_BitOr ); 1871 assert( TK_SLASH==OP_Divide ); 1872 assert( TK_LSHIFT==OP_ShiftLeft ); 1873 assert( TK_RSHIFT==OP_ShiftRight ); 1874 assert( TK_CONCAT==OP_Concat ); 1875 sqlite3ExprCode(pParse, pExpr->pLeft); 1876 sqlite3ExprCode(pParse, pExpr->pRight); 1877 sqlite3VdbeAddOp(v, op, 0, 0); 1878 stackChng = -1; 1879 break; 1880 } 1881 case TK_UMINUS: { 1882 Expr *pLeft = pExpr->pLeft; 1883 assert( pLeft ); 1884 if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){ 1885 Token *p = &pLeft->token; 1886 char *z = sqlite3MPrintf(pParse->db, "-%.*s", p->n, p->z); 1887 if( pLeft->op==TK_FLOAT ){ 1888 sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1); 1889 }else{ 1890 codeInteger(v, z, p->n+1); 1891 } 1892 sqlite3_free(z); 1893 break; 1894 } 1895 /* Fall through into TK_NOT */ 1896 } 1897 case TK_BITNOT: 1898 case TK_NOT: { 1899 assert( TK_BITNOT==OP_BitNot ); 1900 assert( TK_NOT==OP_Not ); 1901 sqlite3ExprCode(pParse, pExpr->pLeft); 1902 sqlite3VdbeAddOp(v, op, 0, 0); 1903 stackChng = 0; 1904 break; 1905 } 1906 case TK_ISNULL: 1907 case TK_NOTNULL: { 1908 int dest; 1909 assert( TK_ISNULL==OP_IsNull ); 1910 assert( TK_NOTNULL==OP_NotNull ); 1911 sqlite3VdbeAddOp(v, OP_Integer, 1, 0); 1912 sqlite3ExprCode(pParse, pExpr->pLeft); 1913 dest = sqlite3VdbeCurrentAddr(v) + 2; 1914 sqlite3VdbeAddOp(v, op, 1, dest); 1915 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); 1916 stackChng = 0; 1917 break; 1918 } 1919 case TK_AGG_FUNCTION: { 1920 AggInfo *pInfo = pExpr->pAggInfo; 1921 if( pInfo==0 ){ 1922 sqlite3ErrorMsg(pParse, "misuse of aggregate: %T", 1923 &pExpr->span); 1924 }else{ 1925 sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0); 1926 } 1927 break; 1928 } 1929 case TK_CONST_FUNC: 1930 case TK_FUNCTION: { 1931 ExprList *pList = pExpr->pList; 1932 int nExpr = pList ? pList->nExpr : 0; 1933 FuncDef *pDef; 1934 int nId; 1935 const char *zId; 1936 int constMask = 0; 1937 int i; 1938 sqlite3 *db = pParse->db; 1939 u8 enc = ENC(db); 1940 CollSeq *pColl = 0; 1941 1942 zId = (char*)pExpr->token.z; 1943 nId = pExpr->token.n; 1944 pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0); 1945 assert( pDef!=0 ); 1946 nExpr = sqlite3ExprCodeExprList(pParse, pList); 1947 #ifndef SQLITE_OMIT_VIRTUALTABLE 1948 /* Possibly overload the function if the first argument is 1949 ** a virtual table column. 1950 ** 1951 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the 1952 ** second argument, not the first, as the argument to test to 1953 ** see if it is a column in a virtual table. This is done because 1954 ** the left operand of infix functions (the operand we want to 1955 ** control overloading) ends up as the second argument to the 1956 ** function. The expression "A glob B" is equivalent to 1957 ** "glob(B,A). We want to use the A in "A glob B" to test 1958 ** for function overloading. But we use the B term in "glob(B,A)". 1959 */ 1960 if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){ 1961 pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr); 1962 }else if( nExpr>0 ){ 1963 pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr); 1964 } 1965 #endif 1966 for(i=0; i<nExpr && i<32; i++){ 1967 if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){ 1968 constMask |= (1<<i); 1969 } 1970 if( pDef->needCollSeq && !pColl ){ 1971 pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); 1972 } 1973 } 1974 if( pDef->needCollSeq ){ 1975 if( !pColl ) pColl = pParse->db->pDfltColl; 1976 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); 1977 } 1978 sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF); 1979 stackChng = 1-nExpr; 1980 break; 1981 } 1982 #ifndef SQLITE_OMIT_SUBQUERY 1983 case TK_EXISTS: 1984 case TK_SELECT: { 1985 if( pExpr->iColumn==0 ){ 1986 sqlite3CodeSubselect(pParse, pExpr); 1987 } 1988 sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0); 1989 VdbeComment((v, "# load subquery result")); 1990 break; 1991 } 1992 case TK_IN: { 1993 int addr; 1994 char affinity; 1995 int ckOffset = pParse->ckOffset; 1996 sqlite3CodeSubselect(pParse, pExpr); 1997 1998 /* Figure out the affinity to use to create a key from the results 1999 ** of the expression. affinityStr stores a static string suitable for 2000 ** P3 of OP_MakeRecord. 2001 */ 2002 affinity = comparisonAffinity(pExpr); 2003 2004 sqlite3VdbeAddOp(v, OP_Integer, 1, 0); 2005 pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0); 2006 2007 /* Code the <expr> from "<expr> IN (...)". The temporary table 2008 ** pExpr->iTable contains the values that make up the (...) set. 2009 */ 2010 sqlite3ExprCode(pParse, pExpr->pLeft); 2011 addr = sqlite3VdbeCurrentAddr(v); 2012 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4); /* addr + 0 */ 2013 sqlite3VdbeAddOp(v, OP_Pop, 2, 0); 2014 sqlite3VdbeAddOp(v, OP_Null, 0, 0); 2015 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7); 2016 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); /* addr + 4 */ 2017 sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7); 2018 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); /* addr + 6 */ 2019 2020 break; 2021 } 2022 #endif 2023 case TK_BETWEEN: { 2024 Expr *pLeft = pExpr->pLeft; 2025 struct ExprList_item *pLItem = pExpr->pList->a; 2026 Expr *pRight = pLItem->pExpr; 2027 sqlite3ExprCode(pParse, pLeft); 2028 sqlite3VdbeAddOp(v, OP_Dup, 0, 0); 2029 sqlite3ExprCode(pParse, pRight); 2030 codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0); 2031 sqlite3VdbeAddOp(v, OP_Pull, 1, 0); 2032 pLItem++; 2033 pRight = pLItem->pExpr; 2034 sqlite3ExprCode(pParse, pRight); 2035 codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0); 2036 sqlite3VdbeAddOp(v, OP_And, 0, 0); 2037 break; 2038 } 2039 case TK_UPLUS: { 2040 sqlite3ExprCode(pParse, pExpr->pLeft); 2041 stackChng = 0; 2042 break; 2043 } 2044 case TK_CASE: { 2045 int expr_end_label; 2046 int jumpInst; 2047 int nExpr; 2048 int i; 2049 ExprList *pEList; 2050 struct ExprList_item *aListelem; 2051 2052 assert(pExpr->pList); 2053 assert((pExpr->pList->nExpr % 2) == 0); 2054 assert(pExpr->pList->nExpr > 0); 2055 pEList = pExpr->pList; 2056 aListelem = pEList->a; 2057 nExpr = pEList->nExpr; 2058 expr_end_label = sqlite3VdbeMakeLabel(v); 2059 if( pExpr->pLeft ){ 2060 sqlite3ExprCode(pParse, pExpr->pLeft); 2061 } 2062 for(i=0; i<nExpr; i=i+2){ 2063 sqlite3ExprCode(pParse, aListelem[i].pExpr); 2064 if( pExpr->pLeft ){ 2065 sqlite3VdbeAddOp(v, OP_Dup, 1, 1); 2066 jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr, 2067 OP_Ne, 0, 1); 2068 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 2069 }else{ 2070 jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0); 2071 } 2072 sqlite3ExprCode(pParse, aListelem[i+1].pExpr); 2073 sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label); 2074 sqlite3VdbeJumpHere(v, jumpInst); 2075 } 2076 if( pExpr->pLeft ){ 2077 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 2078 } 2079 if( pExpr->pRight ){ 2080 sqlite3ExprCode(pParse, pExpr->pRight); 2081 }else{ 2082 sqlite3VdbeAddOp(v, OP_Null, 0, 0); 2083 } 2084 sqlite3VdbeResolveLabel(v, expr_end_label); 2085 break; 2086 } 2087 #ifndef SQLITE_OMIT_TRIGGER 2088 case TK_RAISE: { 2089 if( !pParse->trigStack ){ 2090 sqlite3ErrorMsg(pParse, 2091 "RAISE() may only be used within a trigger-program"); 2092 return; 2093 } 2094 if( pExpr->iColumn!=OE_Ignore ){ 2095 assert( pExpr->iColumn==OE_Rollback || 2096 pExpr->iColumn == OE_Abort || 2097 pExpr->iColumn == OE_Fail ); 2098 sqlite3DequoteExpr(pParse->db, pExpr); 2099 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 2100 (char*)pExpr->token.z, pExpr->token.n); 2101 } else { 2102 assert( pExpr->iColumn == OE_Ignore ); 2103 sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0); 2104 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump); 2105 VdbeComment((v, "# raise(IGNORE)")); 2106 } 2107 stackChng = 0; 2108 break; 2109 } 2110 #endif 2111 } 2112 2113 if( pParse->ckOffset ){ 2114 pParse->ckOffset += stackChng; 2115 assert( pParse->ckOffset ); 2116 } 2117 } 2118 2119 #ifndef SQLITE_OMIT_TRIGGER 2120 /* 2121 ** Generate code that evalutes the given expression and leaves the result 2122 ** on the stack. See also sqlite3ExprCode(). 2123 ** 2124 ** This routine might also cache the result and modify the pExpr tree 2125 ** so that it will make use of the cached result on subsequent evaluations 2126 ** rather than evaluate the whole expression again. Trivial expressions are 2127 ** not cached. If the expression is cached, its result is stored in a 2128 ** memory location. 2129 */ 2130 void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){ 2131 Vdbe *v = pParse->pVdbe; 2132 int iMem; 2133 int addr1, addr2; 2134 if( v==0 ) return; 2135 addr1 = sqlite3VdbeCurrentAddr(v); 2136 sqlite3ExprCode(pParse, pExpr); 2137 addr2 = sqlite3VdbeCurrentAddr(v); 2138 if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){ 2139 iMem = pExpr->iTable = pParse->nMem++; 2140 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0); 2141 pExpr->op = TK_REGISTER; 2142 } 2143 } 2144 #endif 2145 2146 /* 2147 ** Generate code that pushes the value of every element of the given 2148 ** expression list onto the stack. 2149 ** 2150 ** Return the number of elements pushed onto the stack. 2151 */ 2152 int sqlite3ExprCodeExprList( 2153 Parse *pParse, /* Parsing context */ 2154 ExprList *pList /* The expression list to be coded */ 2155 ){ 2156 struct ExprList_item *pItem; 2157 int i, n; 2158 if( pList==0 ) return 0; 2159 n = pList->nExpr; 2160 for(pItem=pList->a, i=n; i>0; i--, pItem++){ 2161 sqlite3ExprCode(pParse, pItem->pExpr); 2162 } 2163 return n; 2164 } 2165 2166 /* 2167 ** Generate code for a boolean expression such that a jump is made 2168 ** to the label "dest" if the expression is true but execution 2169 ** continues straight thru if the expression is false. 2170 ** 2171 ** If the expression evaluates to NULL (neither true nor false), then 2172 ** take the jump if the jumpIfNull flag is true. 2173 ** 2174 ** This code depends on the fact that certain token values (ex: TK_EQ) 2175 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding 2176 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in 2177 ** the make process cause these values to align. Assert()s in the code 2178 ** below verify that the numbers are aligned correctly. 2179 */ 2180 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 2181 Vdbe *v = pParse->pVdbe; 2182 int op = 0; 2183 int ckOffset = pParse->ckOffset; 2184 if( v==0 || pExpr==0 ) return; 2185 op = pExpr->op; 2186 switch( op ){ 2187 case TK_AND: { 2188 int d2 = sqlite3VdbeMakeLabel(v); 2189 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull); 2190 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 2191 sqlite3VdbeResolveLabel(v, d2); 2192 break; 2193 } 2194 case TK_OR: { 2195 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 2196 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 2197 break; 2198 } 2199 case TK_NOT: { 2200 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 2201 break; 2202 } 2203 case TK_LT: 2204 case TK_LE: 2205 case TK_GT: 2206 case TK_GE: 2207 case TK_NE: 2208 case TK_EQ: { 2209 assert( TK_LT==OP_Lt ); 2210 assert( TK_LE==OP_Le ); 2211 assert( TK_GT==OP_Gt ); 2212 assert( TK_GE==OP_Ge ); 2213 assert( TK_EQ==OP_Eq ); 2214 assert( TK_NE==OP_Ne ); 2215 sqlite3ExprCode(pParse, pExpr->pLeft); 2216 sqlite3ExprCode(pParse, pExpr->pRight); 2217 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull); 2218 break; 2219 } 2220 case TK_ISNULL: 2221 case TK_NOTNULL: { 2222 assert( TK_ISNULL==OP_IsNull ); 2223 assert( TK_NOTNULL==OP_NotNull ); 2224 sqlite3ExprCode(pParse, pExpr->pLeft); 2225 sqlite3VdbeAddOp(v, op, 1, dest); 2226 break; 2227 } 2228 case TK_BETWEEN: { 2229 /* The expression "x BETWEEN y AND z" is implemented as: 2230 ** 2231 ** 1 IF (x < y) GOTO 3 2232 ** 2 IF (x <= z) GOTO <dest> 2233 ** 3 ... 2234 */ 2235 int addr; 2236 Expr *pLeft = pExpr->pLeft; 2237 Expr *pRight = pExpr->pList->a[0].pExpr; 2238 sqlite3ExprCode(pParse, pLeft); 2239 sqlite3VdbeAddOp(v, OP_Dup, 0, 0); 2240 sqlite3ExprCode(pParse, pRight); 2241 addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull); 2242 2243 pRight = pExpr->pList->a[1].pExpr; 2244 sqlite3ExprCode(pParse, pRight); 2245 codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull); 2246 2247 sqlite3VdbeAddOp(v, OP_Integer, 0, 0); 2248 sqlite3VdbeJumpHere(v, addr); 2249 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 2250 break; 2251 } 2252 default: { 2253 sqlite3ExprCode(pParse, pExpr); 2254 sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest); 2255 break; 2256 } 2257 } 2258 pParse->ckOffset = ckOffset; 2259 } 2260 2261 /* 2262 ** Generate code for a boolean expression such that a jump is made 2263 ** to the label "dest" if the expression is false but execution 2264 ** continues straight thru if the expression is true. 2265 ** 2266 ** If the expression evaluates to NULL (neither true nor false) then 2267 ** jump if jumpIfNull is true or fall through if jumpIfNull is false. 2268 */ 2269 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 2270 Vdbe *v = pParse->pVdbe; 2271 int op = 0; 2272 int ckOffset = pParse->ckOffset; 2273 if( v==0 || pExpr==0 ) return; 2274 2275 /* The value of pExpr->op and op are related as follows: 2276 ** 2277 ** pExpr->op op 2278 ** --------- ---------- 2279 ** TK_ISNULL OP_NotNull 2280 ** TK_NOTNULL OP_IsNull 2281 ** TK_NE OP_Eq 2282 ** TK_EQ OP_Ne 2283 ** TK_GT OP_Le 2284 ** TK_LE OP_Gt 2285 ** TK_GE OP_Lt 2286 ** TK_LT OP_Ge 2287 ** 2288 ** For other values of pExpr->op, op is undefined and unused. 2289 ** The value of TK_ and OP_ constants are arranged such that we 2290 ** can compute the mapping above using the following expression. 2291 ** Assert()s verify that the computation is correct. 2292 */ 2293 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); 2294 2295 /* Verify correct alignment of TK_ and OP_ constants 2296 */ 2297 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); 2298 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); 2299 assert( pExpr->op!=TK_NE || op==OP_Eq ); 2300 assert( pExpr->op!=TK_EQ || op==OP_Ne ); 2301 assert( pExpr->op!=TK_LT || op==OP_Ge ); 2302 assert( pExpr->op!=TK_LE || op==OP_Gt ); 2303 assert( pExpr->op!=TK_GT || op==OP_Le ); 2304 assert( pExpr->op!=TK_GE || op==OP_Lt ); 2305 2306 switch( pExpr->op ){ 2307 case TK_AND: { 2308 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 2309 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 2310 break; 2311 } 2312 case TK_OR: { 2313 int d2 = sqlite3VdbeMakeLabel(v); 2314 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull); 2315 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 2316 sqlite3VdbeResolveLabel(v, d2); 2317 break; 2318 } 2319 case TK_NOT: { 2320 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 2321 break; 2322 } 2323 case TK_LT: 2324 case TK_LE: 2325 case TK_GT: 2326 case TK_GE: 2327 case TK_NE: 2328 case TK_EQ: { 2329 sqlite3ExprCode(pParse, pExpr->pLeft); 2330 sqlite3ExprCode(pParse, pExpr->pRight); 2331 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull); 2332 break; 2333 } 2334 case TK_ISNULL: 2335 case TK_NOTNULL: { 2336 sqlite3ExprCode(pParse, pExpr->pLeft); 2337 sqlite3VdbeAddOp(v, op, 1, dest); 2338 break; 2339 } 2340 case TK_BETWEEN: { 2341 /* The expression is "x BETWEEN y AND z". It is implemented as: 2342 ** 2343 ** 1 IF (x >= y) GOTO 3 2344 ** 2 GOTO <dest> 2345 ** 3 IF (x > z) GOTO <dest> 2346 */ 2347 int addr; 2348 Expr *pLeft = pExpr->pLeft; 2349 Expr *pRight = pExpr->pList->a[0].pExpr; 2350 sqlite3ExprCode(pParse, pLeft); 2351 sqlite3VdbeAddOp(v, OP_Dup, 0, 0); 2352 sqlite3ExprCode(pParse, pRight); 2353 addr = sqlite3VdbeCurrentAddr(v); 2354 codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull); 2355 2356 sqlite3VdbeAddOp(v, OP_Pop, 1, 0); 2357 sqlite3VdbeAddOp(v, OP_Goto, 0, dest); 2358 pRight = pExpr->pList->a[1].pExpr; 2359 sqlite3ExprCode(pParse, pRight); 2360 codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull); 2361 break; 2362 } 2363 default: { 2364 sqlite3ExprCode(pParse, pExpr); 2365 sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest); 2366 break; 2367 } 2368 } 2369 pParse->ckOffset = ckOffset; 2370 } 2371 2372 /* 2373 ** Do a deep comparison of two expression trees. Return TRUE (non-zero) 2374 ** if they are identical and return FALSE if they differ in any way. 2375 ** 2376 ** Sometimes this routine will return FALSE even if the two expressions 2377 ** really are equivalent. If we cannot prove that the expressions are 2378 ** identical, we return FALSE just to be safe. So if this routine 2379 ** returns false, then you do not really know for certain if the two 2380 ** expressions are the same. But if you get a TRUE return, then you 2381 ** can be sure the expressions are the same. In the places where 2382 ** this routine is used, it does not hurt to get an extra FALSE - that 2383 ** just might result in some slightly slower code. But returning 2384 ** an incorrect TRUE could lead to a malfunction. 2385 */ 2386 int sqlite3ExprCompare(Expr *pA, Expr *pB){ 2387 int i; 2388 if( pA==0||pB==0 ){ 2389 return pB==pA; 2390 } 2391 if( pA->op!=pB->op ) return 0; 2392 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0; 2393 if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0; 2394 if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0; 2395 if( pA->pList ){ 2396 if( pB->pList==0 ) return 0; 2397 if( pA->pList->nExpr!=pB->pList->nExpr ) return 0; 2398 for(i=0; i<pA->pList->nExpr; i++){ 2399 if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){ 2400 return 0; 2401 } 2402 } 2403 }else if( pB->pList ){ 2404 return 0; 2405 } 2406 if( pA->pSelect || pB->pSelect ) return 0; 2407 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0; 2408 if( pA->op!=TK_COLUMN && pA->token.z ){ 2409 if( pB->token.z==0 ) return 0; 2410 if( pB->token.n!=pA->token.n ) return 0; 2411 if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){ 2412 return 0; 2413 } 2414 } 2415 return 1; 2416 } 2417 2418 2419 /* 2420 ** Add a new element to the pAggInfo->aCol[] array. Return the index of 2421 ** the new element. Return a negative number if malloc fails. 2422 */ 2423 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ 2424 int i; 2425 pInfo->aCol = sqlite3ArrayAllocate( 2426 db, 2427 pInfo->aCol, 2428 sizeof(pInfo->aCol[0]), 2429 3, 2430 &pInfo->nColumn, 2431 &pInfo->nColumnAlloc, 2432 &i 2433 ); 2434 return i; 2435 } 2436 2437 /* 2438 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of 2439 ** the new element. Return a negative number if malloc fails. 2440 */ 2441 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ 2442 int i; 2443 pInfo->aFunc = sqlite3ArrayAllocate( 2444 db, 2445 pInfo->aFunc, 2446 sizeof(pInfo->aFunc[0]), 2447 3, 2448 &pInfo->nFunc, 2449 &pInfo->nFuncAlloc, 2450 &i 2451 ); 2452 return i; 2453 } 2454 2455 /* 2456 ** This is an xFunc for walkExprTree() used to implement 2457 ** sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates 2458 ** for additional information. 2459 ** 2460 ** This routine analyzes the aggregate function at pExpr. 2461 */ 2462 static int analyzeAggregate(void *pArg, Expr *pExpr){ 2463 int i; 2464 NameContext *pNC = (NameContext *)pArg; 2465 Parse *pParse = pNC->pParse; 2466 SrcList *pSrcList = pNC->pSrcList; 2467 AggInfo *pAggInfo = pNC->pAggInfo; 2468 2469 switch( pExpr->op ){ 2470 case TK_AGG_COLUMN: 2471 case TK_COLUMN: { 2472 /* Check to see if the column is in one of the tables in the FROM 2473 ** clause of the aggregate query */ 2474 if( pSrcList ){ 2475 struct SrcList_item *pItem = pSrcList->a; 2476 for(i=0; i<pSrcList->nSrc; i++, pItem++){ 2477 struct AggInfo_col *pCol; 2478 if( pExpr->iTable==pItem->iCursor ){ 2479 /* If we reach this point, it means that pExpr refers to a table 2480 ** that is in the FROM clause of the aggregate query. 2481 ** 2482 ** Make an entry for the column in pAggInfo->aCol[] if there 2483 ** is not an entry there already. 2484 */ 2485 int k; 2486 pCol = pAggInfo->aCol; 2487 for(k=0; k<pAggInfo->nColumn; k++, pCol++){ 2488 if( pCol->iTable==pExpr->iTable && 2489 pCol->iColumn==pExpr->iColumn ){ 2490 break; 2491 } 2492 } 2493 if( (k>=pAggInfo->nColumn) 2494 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 2495 ){ 2496 pCol = &pAggInfo->aCol[k]; 2497 pCol->pTab = pExpr->pTab; 2498 pCol->iTable = pExpr->iTable; 2499 pCol->iColumn = pExpr->iColumn; 2500 pCol->iMem = pParse->nMem++; 2501 pCol->iSorterColumn = -1; 2502 pCol->pExpr = pExpr; 2503 if( pAggInfo->pGroupBy ){ 2504 int j, n; 2505 ExprList *pGB = pAggInfo->pGroupBy; 2506 struct ExprList_item *pTerm = pGB->a; 2507 n = pGB->nExpr; 2508 for(j=0; j<n; j++, pTerm++){ 2509 Expr *pE = pTerm->pExpr; 2510 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && 2511 pE->iColumn==pExpr->iColumn ){ 2512 pCol->iSorterColumn = j; 2513 break; 2514 } 2515 } 2516 } 2517 if( pCol->iSorterColumn<0 ){ 2518 pCol->iSorterColumn = pAggInfo->nSortingColumn++; 2519 } 2520 } 2521 /* There is now an entry for pExpr in pAggInfo->aCol[] (either 2522 ** because it was there before or because we just created it). 2523 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that 2524 ** pAggInfo->aCol[] entry. 2525 */ 2526 pExpr->pAggInfo = pAggInfo; 2527 pExpr->op = TK_AGG_COLUMN; 2528 pExpr->iAgg = k; 2529 break; 2530 } /* endif pExpr->iTable==pItem->iCursor */ 2531 } /* end loop over pSrcList */ 2532 } 2533 return 1; 2534 } 2535 case TK_AGG_FUNCTION: { 2536 /* The pNC->nDepth==0 test causes aggregate functions in subqueries 2537 ** to be ignored */ 2538 if( pNC->nDepth==0 ){ 2539 /* Check to see if pExpr is a duplicate of another aggregate 2540 ** function that is already in the pAggInfo structure 2541 */ 2542 struct AggInfo_func *pItem = pAggInfo->aFunc; 2543 for(i=0; i<pAggInfo->nFunc; i++, pItem++){ 2544 if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){ 2545 break; 2546 } 2547 } 2548 if( i>=pAggInfo->nFunc ){ 2549 /* pExpr is original. Make a new entry in pAggInfo->aFunc[] 2550 */ 2551 u8 enc = ENC(pParse->db); 2552 i = addAggInfoFunc(pParse->db, pAggInfo); 2553 if( i>=0 ){ 2554 pItem = &pAggInfo->aFunc[i]; 2555 pItem->pExpr = pExpr; 2556 pItem->iMem = pParse->nMem++; 2557 pItem->pFunc = sqlite3FindFunction(pParse->db, 2558 (char*)pExpr->token.z, pExpr->token.n, 2559 pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0); 2560 if( pExpr->flags & EP_Distinct ){ 2561 pItem->iDistinct = pParse->nTab++; 2562 }else{ 2563 pItem->iDistinct = -1; 2564 } 2565 } 2566 } 2567 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry 2568 */ 2569 pExpr->iAgg = i; 2570 pExpr->pAggInfo = pAggInfo; 2571 return 1; 2572 } 2573 } 2574 } 2575 2576 /* Recursively walk subqueries looking for TK_COLUMN nodes that need 2577 ** to be changed to TK_AGG_COLUMN. But increment nDepth so that 2578 ** TK_AGG_FUNCTION nodes in subqueries will be unchanged. 2579 */ 2580 if( pExpr->pSelect ){ 2581 pNC->nDepth++; 2582 walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC); 2583 pNC->nDepth--; 2584 } 2585 return 0; 2586 } 2587 2588 /* 2589 ** Analyze the given expression looking for aggregate functions and 2590 ** for variables that need to be added to the pParse->aAgg[] array. 2591 ** Make additional entries to the pParse->aAgg[] array as necessary. 2592 ** 2593 ** This routine should only be called after the expression has been 2594 ** analyzed by sqlite3ExprResolveNames(). 2595 ** 2596 ** If errors are seen, leave an error message in zErrMsg and return 2597 ** the number of errors. 2598 */ 2599 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ 2600 int nErr = pNC->pParse->nErr; 2601 walkExprTree(pExpr, analyzeAggregate, pNC); 2602 return pNC->pParse->nErr - nErr; 2603 } 2604 2605 /* 2606 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an 2607 ** expression list. Return the number of errors. 2608 ** 2609 ** If an error is found, the analysis is cut short. 2610 */ 2611 int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ 2612 struct ExprList_item *pItem; 2613 int i; 2614 int nErr = 0; 2615 if( pList ){ 2616 for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){ 2617 nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); 2618 } 2619 } 2620 return nErr; 2621 } 2622