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