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