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