1 /* 2 ** 2008 August 18 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 ** 13 ** This file contains routines used for walking the parser tree and 14 ** resolve all identifiers by associating them with a particular 15 ** table and column. 16 ** 17 ** $Id: resolve.c,v 1.20 2009/03/05 04:23:47 shane Exp $ 18 */ 19 #include "sqliteInt.h" 20 #include <stdlib.h> 21 #include <string.h> 22 23 /* 24 ** Turn the pExpr expression into an alias for the iCol-th column of the 25 ** result set in pEList. 26 ** 27 ** If the result set column is a simple column reference, then this routine 28 ** makes an exact copy. But for any other kind of expression, this 29 ** routine make a copy of the result set column as the argument to the 30 ** TK_AS operator. The TK_AS operator causes the expression to be 31 ** evaluated just once and then reused for each alias. 32 ** 33 ** The reason for suppressing the TK_AS term when the expression is a simple 34 ** column reference is so that the column reference will be recognized as 35 ** usable by indices within the WHERE clause processing logic. 36 ** 37 ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means 38 ** that in a GROUP BY clause, the expression is evaluated twice. Hence: 39 ** 40 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x 41 ** 42 ** Is equivalent to: 43 ** 44 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5 45 ** 46 ** The result of random()%5 in the GROUP BY clause is probably different 47 ** from the result in the result-set. We might fix this someday. Or 48 ** then again, we might not... 49 */ 50 static void resolveAlias( 51 Parse *pParse, /* Parsing context */ 52 ExprList *pEList, /* A result set */ 53 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ 54 Expr *pExpr, /* Transform this into an alias to the result set */ 55 const char *zType /* "GROUP" or "ORDER" or "" */ 56 ){ 57 Expr *pOrig; /* The iCol-th column of the result set */ 58 Expr *pDup; /* Copy of pOrig */ 59 sqlite3 *db; /* The database connection */ 60 61 assert( iCol>=0 && iCol<pEList->nExpr ); 62 pOrig = pEList->a[iCol].pExpr; 63 assert( pOrig!=0 ); 64 assert( pOrig->flags & EP_Resolved ); 65 db = pParse->db; 66 pDup = sqlite3ExprDup(db, pOrig, 0); 67 if( pDup==0 ) return; 68 sqlite3TokenCopy(db, &pDup->token, &pOrig->token); 69 if( pDup->op!=TK_COLUMN && zType[0]!='G' ){ 70 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0); 71 if( pDup==0 ) return; 72 if( pEList->a[iCol].iAlias==0 ){ 73 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias); 74 } 75 pDup->iTable = pEList->a[iCol].iAlias; 76 } 77 if( pExpr->flags & EP_ExpCollate ){ 78 pDup->pColl = pExpr->pColl; 79 pDup->flags |= EP_ExpCollate; 80 } 81 sqlite3ExprClear(db, pExpr); 82 memcpy(pExpr, pDup, sizeof(*pExpr)); 83 sqlite3DbFree(db, pDup); 84 } 85 86 /* 87 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up 88 ** that name in the set of source tables in pSrcList and make the pExpr 89 ** expression node refer back to that source column. The following changes 90 ** are made to pExpr: 91 ** 92 ** pExpr->iDb Set the index in db->aDb[] of the database X 93 ** (even if X is implied). 94 ** pExpr->iTable Set to the cursor number for the table obtained 95 ** from pSrcList. 96 ** pExpr->pTab Points to the Table structure of X.Y (even if 97 ** X and/or Y are implied.) 98 ** pExpr->iColumn Set to the column number within the table. 99 ** pExpr->op Set to TK_COLUMN. 100 ** pExpr->pLeft Any expression this points to is deleted 101 ** pExpr->pRight Any expression this points to is deleted. 102 ** 103 ** The pDbToken is the name of the database (the "X"). This value may be 104 ** NULL meaning that name is of the form Y.Z or Z. Any available database 105 ** can be used. The pTableToken is the name of the table (the "Y"). This 106 ** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it 107 ** means that the form of the name is Z and that columns from any table 108 ** can be used. 109 ** 110 ** If the name cannot be resolved unambiguously, leave an error message 111 ** in pParse and return non-zero. Return zero on success. 112 */ 113 static int lookupName( 114 Parse *pParse, /* The parsing context */ 115 Token *pDbToken, /* Name of the database containing table, or NULL */ 116 Token *pTableToken, /* Name of table containing column, or NULL */ 117 Token *pColumnToken, /* Name of the column. */ 118 NameContext *pNC, /* The name context used to resolve the name */ 119 Expr *pExpr /* Make this EXPR node point to the selected column */ 120 ){ 121 char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */ 122 char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */ 123 char *zCol = 0; /* Name of the column. The "Z" */ 124 int i, j; /* Loop counters */ 125 int cnt = 0; /* Number of matching column names */ 126 int cntTab = 0; /* Number of matching table names */ 127 sqlite3 *db = pParse->db; /* The database connection */ 128 struct SrcList_item *pItem; /* Use for looping over pSrcList items */ 129 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ 130 NameContext *pTopNC = pNC; /* First namecontext in the list */ 131 Schema *pSchema = 0; /* Schema of the expression */ 132 133 assert( pNC ); /* the name context cannot be NULL. */ 134 assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */ 135 136 /* Dequote and zero-terminate the names */ 137 zDb = sqlite3NameFromToken(db, pDbToken); 138 zTab = sqlite3NameFromToken(db, pTableToken); 139 zCol = sqlite3NameFromToken(db, pColumnToken); 140 if( db->mallocFailed ){ 141 goto lookupname_end; 142 } 143 144 /* Initialize the node to no-match */ 145 pExpr->iTable = -1; 146 pExpr->pTab = 0; 147 148 /* Start at the inner-most context and move outward until a match is found */ 149 while( pNC && cnt==0 ){ 150 ExprList *pEList; 151 SrcList *pSrcList = pNC->pSrcList; 152 153 if( pSrcList ){ 154 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ 155 Table *pTab; 156 int iDb; 157 Column *pCol; 158 159 pTab = pItem->pTab; 160 assert( pTab!=0 && pTab->zName!=0 ); 161 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 162 assert( pTab->nCol>0 ); 163 if( zTab ){ 164 if( pItem->zAlias ){ 165 char *zTabName = pItem->zAlias; 166 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue; 167 }else{ 168 char *zTabName = pTab->zName; 169 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue; 170 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){ 171 continue; 172 } 173 } 174 } 175 if( 0==(cntTab++) ){ 176 pExpr->iTable = pItem->iCursor; 177 pExpr->pTab = pTab; 178 pSchema = pTab->pSchema; 179 pMatch = pItem; 180 } 181 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ 182 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ 183 IdList *pUsing; 184 cnt++; 185 pExpr->iTable = pItem->iCursor; 186 pExpr->pTab = pTab; 187 pMatch = pItem; 188 pSchema = pTab->pSchema; 189 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ 190 pExpr->iColumn = j==pTab->iPKey ? -1 : j; 191 if( i<pSrcList->nSrc-1 ){ 192 if( pItem[1].jointype & JT_NATURAL ){ 193 /* If this match occurred in the left table of a natural join, 194 ** then skip the right table to avoid a duplicate match */ 195 pItem++; 196 i++; 197 }else if( (pUsing = pItem[1].pUsing)!=0 ){ 198 /* If this match occurs on a column that is in the USING clause 199 ** of a join, skip the search of the right table of the join 200 ** to avoid a duplicate match there. */ 201 int k; 202 for(k=0; k<pUsing->nId; k++){ 203 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){ 204 pItem++; 205 i++; 206 break; 207 } 208 } 209 } 210 } 211 break; 212 } 213 } 214 } 215 } 216 217 #ifndef SQLITE_OMIT_TRIGGER 218 /* If we have not already resolved the name, then maybe 219 ** it is a new.* or old.* trigger argument reference 220 */ 221 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){ 222 TriggerStack *pTriggerStack = pParse->trigStack; 223 Table *pTab = 0; 224 u32 *piColMask = 0; 225 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){ 226 pExpr->iTable = pTriggerStack->newIdx; 227 assert( pTriggerStack->pTab ); 228 pTab = pTriggerStack->pTab; 229 piColMask = &(pTriggerStack->newColMask); 230 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){ 231 pExpr->iTable = pTriggerStack->oldIdx; 232 assert( pTriggerStack->pTab ); 233 pTab = pTriggerStack->pTab; 234 piColMask = &(pTriggerStack->oldColMask); 235 } 236 237 if( pTab ){ 238 int iCol; 239 Column *pCol = pTab->aCol; 240 241 pSchema = pTab->pSchema; 242 cntTab++; 243 for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) { 244 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ 245 cnt++; 246 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol; 247 pExpr->pTab = pTab; 248 if( iCol>=0 ){ 249 testcase( iCol==31 ); 250 testcase( iCol==32 ); 251 *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0); 252 } 253 break; 254 } 255 } 256 } 257 } 258 #endif /* !defined(SQLITE_OMIT_TRIGGER) */ 259 260 /* 261 ** Perhaps the name is a reference to the ROWID 262 */ 263 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){ 264 cnt = 1; 265 pExpr->iColumn = -1; 266 pExpr->affinity = SQLITE_AFF_INTEGER; 267 } 268 269 /* 270 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z 271 ** might refer to an result-set alias. This happens, for example, when 272 ** we are resolving names in the WHERE clause of the following command: 273 ** 274 ** SELECT a+b AS x FROM table WHERE x<10; 275 ** 276 ** In cases like this, replace pExpr with a copy of the expression that 277 ** forms the result set entry ("a+b" in the example) and return immediately. 278 ** Note that the expression in the result set should have already been 279 ** resolved by the time the WHERE clause is resolved. 280 */ 281 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){ 282 for(j=0; j<pEList->nExpr; j++){ 283 char *zAs = pEList->a[j].zName; 284 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 285 Expr *pOrig; 286 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 287 assert( pExpr->x.pList==0 ); 288 assert( pExpr->x.pSelect==0 ); 289 pOrig = pEList->a[j].pExpr; 290 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){ 291 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); 292 sqlite3DbFree(db, zCol); 293 return 2; 294 } 295 resolveAlias(pParse, pEList, j, pExpr, ""); 296 cnt = 1; 297 pMatch = 0; 298 assert( zTab==0 && zDb==0 ); 299 goto lookupname_end_2; 300 } 301 } 302 } 303 304 /* Advance to the next name context. The loop will exit when either 305 ** we have a match (cnt>0) or when we run out of name contexts. 306 */ 307 if( cnt==0 ){ 308 pNC = pNC->pNext; 309 } 310 } 311 312 /* 313 ** If X and Y are NULL (in other words if only the column name Z is 314 ** supplied) and the value of Z is enclosed in double-quotes, then 315 ** Z is a string literal if it doesn't match any column names. In that 316 ** case, we need to return right away and not make any changes to 317 ** pExpr. 318 ** 319 ** Because no reference was made to outer contexts, the pNC->nRef 320 ** fields are not changed in any context. 321 */ 322 if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){ 323 sqlite3DbFree(db, zCol); 324 pExpr->op = TK_STRING; 325 pExpr->pTab = 0; 326 return 0; 327 } 328 329 /* 330 ** cnt==0 means there was not match. cnt>1 means there were two or 331 ** more matches. Either way, we have an error. 332 */ 333 if( cnt!=1 ){ 334 const char *zErr; 335 zErr = cnt==0 ? "no such column" : "ambiguous column name"; 336 if( zDb ){ 337 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); 338 }else if( zTab ){ 339 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); 340 }else{ 341 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); 342 } 343 pTopNC->nErr++; 344 } 345 346 /* If a column from a table in pSrcList is referenced, then record 347 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes 348 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the 349 ** column number is greater than the number of bits in the bitmask 350 ** then set the high-order bit of the bitmask. 351 */ 352 if( pExpr->iColumn>=0 && pMatch!=0 ){ 353 int n = pExpr->iColumn; 354 testcase( n==BMS-1 ); 355 if( n>=BMS ){ 356 n = BMS-1; 357 } 358 assert( pMatch->iCursor==pExpr->iTable ); 359 pMatch->colUsed |= ((Bitmask)1)<<n; 360 } 361 362 lookupname_end: 363 /* Clean up and return 364 */ 365 sqlite3DbFree(db, zDb); 366 sqlite3DbFree(db, zTab); 367 sqlite3ExprDelete(db, pExpr->pLeft); 368 pExpr->pLeft = 0; 369 sqlite3ExprDelete(db, pExpr->pRight); 370 pExpr->pRight = 0; 371 pExpr->op = TK_COLUMN; 372 lookupname_end_2: 373 sqlite3DbFree(db, zCol); 374 if( cnt==1 ){ 375 assert( pNC!=0 ); 376 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); 377 /* Increment the nRef value on all name contexts from TopNC up to 378 ** the point where the name matched. */ 379 for(;;){ 380 assert( pTopNC!=0 ); 381 pTopNC->nRef++; 382 if( pTopNC==pNC ) break; 383 pTopNC = pTopNC->pNext; 384 } 385 return 0; 386 } else { 387 return 1; 388 } 389 } 390 391 /* 392 ** This routine is callback for sqlite3WalkExpr(). 393 ** 394 ** Resolve symbolic names into TK_COLUMN operators for the current 395 ** node in the expression tree. Return 0 to continue the search down 396 ** the tree or 2 to abort the tree walk. 397 ** 398 ** This routine also does error checking and name resolution for 399 ** function names. The operator for aggregate functions is changed 400 ** to TK_AGG_FUNCTION. 401 */ 402 static int resolveExprStep(Walker *pWalker, Expr *pExpr){ 403 NameContext *pNC; 404 Parse *pParse; 405 406 pNC = pWalker->u.pNC; 407 assert( pNC!=0 ); 408 pParse = pNC->pParse; 409 assert( pParse==pWalker->pParse ); 410 411 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune; 412 ExprSetProperty(pExpr, EP_Resolved); 413 #ifndef NDEBUG 414 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ 415 SrcList *pSrcList = pNC->pSrcList; 416 int i; 417 for(i=0; i<pNC->pSrcList->nSrc; i++){ 418 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab); 419 } 420 } 421 #endif 422 switch( pExpr->op ){ 423 424 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) 425 /* The special operator TK_ROW means use the rowid for the first 426 ** column in the FROM clause. This is used by the LIMIT and ORDER BY 427 ** clause processing on UPDATE and DELETE statements. 428 */ 429 case TK_ROW: { 430 SrcList *pSrcList = pNC->pSrcList; 431 struct SrcList_item *pItem; 432 assert( pSrcList && pSrcList->nSrc==1 ); 433 pItem = pSrcList->a; 434 pExpr->op = TK_COLUMN; 435 pExpr->pTab = pItem->pTab; 436 pExpr->iTable = pItem->iCursor; 437 pExpr->iColumn = -1; 438 pExpr->affinity = SQLITE_AFF_INTEGER; 439 break; 440 } 441 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */ 442 443 /* A lone identifier is the name of a column. 444 */ 445 case TK_ID: { 446 lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr); 447 return WRC_Prune; 448 } 449 450 /* A table name and column name: ID.ID 451 ** Or a database, table and column: ID.ID.ID 452 */ 453 case TK_DOT: { 454 Token *pColumn; 455 Token *pTable; 456 Token *pDb; 457 Expr *pRight; 458 459 /* if( pSrcList==0 ) break; */ 460 pRight = pExpr->pRight; 461 if( pRight->op==TK_ID ){ 462 pDb = 0; 463 pTable = &pExpr->pLeft->token; 464 pColumn = &pRight->token; 465 }else{ 466 assert( pRight->op==TK_DOT ); 467 pDb = &pExpr->pLeft->token; 468 pTable = &pRight->pLeft->token; 469 pColumn = &pRight->pRight->token; 470 } 471 lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr); 472 return WRC_Prune; 473 } 474 475 /* Resolve function names 476 */ 477 case TK_CONST_FUNC: 478 case TK_FUNCTION: { 479 ExprList *pList = pExpr->x.pList; /* The argument list */ 480 int n = pList ? pList->nExpr : 0; /* Number of arguments */ 481 int no_such_func = 0; /* True if no such function exists */ 482 int wrong_num_args = 0; /* True if wrong number of arguments */ 483 int is_agg = 0; /* True if is an aggregate function */ 484 int auth; /* Authorization to use the function */ 485 int nId; /* Number of characters in function name */ 486 const char *zId; /* The function name. */ 487 FuncDef *pDef; /* Information about the function */ 488 u8 enc = ENC(pParse->db); /* The database encoding */ 489 490 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 491 zId = (char*)pExpr->token.z; 492 nId = pExpr->token.n; 493 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0); 494 if( pDef==0 ){ 495 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0); 496 if( pDef==0 ){ 497 no_such_func = 1; 498 }else{ 499 wrong_num_args = 1; 500 } 501 }else{ 502 is_agg = pDef->xFunc==0; 503 } 504 #ifndef SQLITE_OMIT_AUTHORIZATION 505 if( pDef ){ 506 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0); 507 if( auth!=SQLITE_OK ){ 508 if( auth==SQLITE_DENY ){ 509 sqlite3ErrorMsg(pParse, "not authorized to use function: %s", 510 pDef->zName); 511 pNC->nErr++; 512 } 513 pExpr->op = TK_NULL; 514 return WRC_Prune; 515 } 516 } 517 #endif 518 if( is_agg && !pNC->allowAgg ){ 519 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId); 520 pNC->nErr++; 521 is_agg = 0; 522 }else if( no_such_func ){ 523 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); 524 pNC->nErr++; 525 }else if( wrong_num_args ){ 526 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", 527 nId, zId); 528 pNC->nErr++; 529 } 530 if( is_agg ){ 531 pExpr->op = TK_AGG_FUNCTION; 532 pNC->hasAgg = 1; 533 } 534 if( is_agg ) pNC->allowAgg = 0; 535 sqlite3WalkExprList(pWalker, pList); 536 if( is_agg ) pNC->allowAgg = 1; 537 /* FIX ME: Compute pExpr->affinity based on the expected return 538 ** type of the function 539 */ 540 return WRC_Prune; 541 } 542 #ifndef SQLITE_OMIT_SUBQUERY 543 case TK_SELECT: 544 case TK_EXISTS: 545 #endif 546 case TK_IN: { 547 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 548 int nRef = pNC->nRef; 549 #ifndef SQLITE_OMIT_CHECK 550 if( pNC->isCheck ){ 551 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints"); 552 } 553 #endif 554 sqlite3WalkSelect(pWalker, pExpr->x.pSelect); 555 assert( pNC->nRef>=nRef ); 556 if( nRef!=pNC->nRef ){ 557 ExprSetProperty(pExpr, EP_VarSelect); 558 } 559 } 560 break; 561 } 562 #ifndef SQLITE_OMIT_CHECK 563 case TK_VARIABLE: { 564 if( pNC->isCheck ){ 565 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints"); 566 } 567 break; 568 } 569 #endif 570 } 571 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; 572 } 573 574 /* 575 ** pEList is a list of expressions which are really the result set of the 576 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. 577 ** This routine checks to see if pE is a simple identifier which corresponds 578 ** to the AS-name of one of the terms of the expression list. If it is, 579 ** this routine return an integer between 1 and N where N is the number of 580 ** elements in pEList, corresponding to the matching entry. If there is 581 ** no match, or if pE is not a simple identifier, then this routine 582 ** return 0. 583 ** 584 ** pEList has been resolved. pE has not. 585 */ 586 static int resolveAsName( 587 Parse *pParse, /* Parsing context for error messages */ 588 ExprList *pEList, /* List of expressions to scan */ 589 Expr *pE /* Expression we are trying to match */ 590 ){ 591 int i; /* Loop counter */ 592 593 if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){ 594 sqlite3 *db = pParse->db; 595 char *zCol = sqlite3NameFromToken(db, &pE->token); 596 if( zCol==0 ){ 597 return -1; 598 } 599 for(i=0; i<pEList->nExpr; i++){ 600 char *zAs = pEList->a[i].zName; 601 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 602 sqlite3DbFree(db, zCol); 603 return i+1; 604 } 605 } 606 sqlite3DbFree(db, zCol); 607 } 608 return 0; 609 } 610 611 /* 612 ** pE is a pointer to an expression which is a single term in the 613 ** ORDER BY of a compound SELECT. The expression has not been 614 ** name resolved. 615 ** 616 ** At the point this routine is called, we already know that the 617 ** ORDER BY term is not an integer index into the result set. That 618 ** case is handled by the calling routine. 619 ** 620 ** Attempt to match pE against result set columns in the left-most 621 ** SELECT statement. Return the index i of the matching column, 622 ** as an indication to the caller that it should sort by the i-th column. 623 ** The left-most column is 1. In other words, the value returned is the 624 ** same integer value that would be used in the SQL statement to indicate 625 ** the column. 626 ** 627 ** If there is no match, return 0. Return -1 if an error occurs. 628 */ 629 static int resolveOrderByTermToExprList( 630 Parse *pParse, /* Parsing context for error messages */ 631 Select *pSelect, /* The SELECT statement with the ORDER BY clause */ 632 Expr *pE /* The specific ORDER BY term */ 633 ){ 634 int i; /* Loop counter */ 635 ExprList *pEList; /* The columns of the result set */ 636 NameContext nc; /* Name context for resolving pE */ 637 638 assert( sqlite3ExprIsInteger(pE, &i)==0 ); 639 pEList = pSelect->pEList; 640 641 /* Resolve all names in the ORDER BY term expression 642 */ 643 memset(&nc, 0, sizeof(nc)); 644 nc.pParse = pParse; 645 nc.pSrcList = pSelect->pSrc; 646 nc.pEList = pEList; 647 nc.allowAgg = 1; 648 nc.nErr = 0; 649 if( sqlite3ResolveExprNames(&nc, pE) ){ 650 sqlite3ErrorClear(pParse); 651 return 0; 652 } 653 654 /* Try to match the ORDER BY expression against an expression 655 ** in the result set. Return an 1-based index of the matching 656 ** result-set entry. 657 */ 658 for(i=0; i<pEList->nExpr; i++){ 659 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){ 660 return i+1; 661 } 662 } 663 664 /* If no match, return 0. */ 665 return 0; 666 } 667 668 /* 669 ** Generate an ORDER BY or GROUP BY term out-of-range error. 670 */ 671 static void resolveOutOfRangeError( 672 Parse *pParse, /* The error context into which to write the error */ 673 const char *zType, /* "ORDER" or "GROUP" */ 674 int i, /* The index (1-based) of the term out of range */ 675 int mx /* Largest permissible value of i */ 676 ){ 677 sqlite3ErrorMsg(pParse, 678 "%r %s BY term out of range - should be " 679 "between 1 and %d", i, zType, mx); 680 } 681 682 /* 683 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify 684 ** each term of the ORDER BY clause is a constant integer between 1 685 ** and N where N is the number of columns in the compound SELECT. 686 ** 687 ** ORDER BY terms that are already an integer between 1 and N are 688 ** unmodified. ORDER BY terms that are integers outside the range of 689 ** 1 through N generate an error. ORDER BY terms that are expressions 690 ** are matched against result set expressions of compound SELECT 691 ** beginning with the left-most SELECT and working toward the right. 692 ** At the first match, the ORDER BY expression is transformed into 693 ** the integer column number. 694 ** 695 ** Return the number of errors seen. 696 */ 697 static int resolveCompoundOrderBy( 698 Parse *pParse, /* Parsing context. Leave error messages here */ 699 Select *pSelect /* The SELECT statement containing the ORDER BY */ 700 ){ 701 int i; 702 ExprList *pOrderBy; 703 ExprList *pEList; 704 sqlite3 *db; 705 int moreToDo = 1; 706 707 pOrderBy = pSelect->pOrderBy; 708 if( pOrderBy==0 ) return 0; 709 db = pParse->db; 710 #if SQLITE_MAX_COLUMN 711 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 712 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); 713 return 1; 714 } 715 #endif 716 for(i=0; i<pOrderBy->nExpr; i++){ 717 pOrderBy->a[i].done = 0; 718 } 719 pSelect->pNext = 0; 720 while( pSelect->pPrior ){ 721 pSelect->pPrior->pNext = pSelect; 722 pSelect = pSelect->pPrior; 723 } 724 while( pSelect && moreToDo ){ 725 struct ExprList_item *pItem; 726 moreToDo = 0; 727 pEList = pSelect->pEList; 728 assert( pEList!=0 ); 729 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 730 int iCol = -1; 731 Expr *pE, *pDup; 732 if( pItem->done ) continue; 733 pE = pItem->pExpr; 734 if( sqlite3ExprIsInteger(pE, &iCol) ){ 735 if( iCol<0 || iCol>pEList->nExpr ){ 736 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); 737 return 1; 738 } 739 }else{ 740 iCol = resolveAsName(pParse, pEList, pE); 741 if( iCol==0 ){ 742 pDup = sqlite3ExprDup(db, pE, 0); 743 if( !db->mallocFailed ){ 744 assert(pDup); 745 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); 746 } 747 sqlite3ExprDelete(db, pDup); 748 } 749 if( iCol<0 ){ 750 return 1; 751 } 752 } 753 if( iCol>0 ){ 754 CollSeq *pColl = pE->pColl; 755 int flags = pE->flags & EP_ExpCollate; 756 sqlite3ExprDelete(db, pE); 757 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0); 758 if( pE==0 ) return 1; 759 pE->pColl = pColl; 760 pE->flags |= EP_IntValue | flags; 761 pE->iTable = iCol; 762 pItem->iCol = (u16)iCol; 763 pItem->done = 1; 764 }else{ 765 moreToDo = 1; 766 } 767 } 768 pSelect = pSelect->pNext; 769 } 770 for(i=0; i<pOrderBy->nExpr; i++){ 771 if( pOrderBy->a[i].done==0 ){ 772 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " 773 "column in the result set", i+1); 774 return 1; 775 } 776 } 777 return 0; 778 } 779 780 /* 781 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of 782 ** the SELECT statement pSelect. If any term is reference to a 783 ** result set expression (as determined by the ExprList.a.iCol field) 784 ** then convert that term into a copy of the corresponding result set 785 ** column. 786 ** 787 ** If any errors are detected, add an error message to pParse and 788 ** return non-zero. Return zero if no errors are seen. 789 */ 790 int sqlite3ResolveOrderGroupBy( 791 Parse *pParse, /* Parsing context. Leave error messages here */ 792 Select *pSelect, /* The SELECT statement containing the clause */ 793 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 794 const char *zType /* "ORDER" or "GROUP" */ 795 ){ 796 int i; 797 sqlite3 *db = pParse->db; 798 ExprList *pEList; 799 struct ExprList_item *pItem; 800 801 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; 802 #if SQLITE_MAX_COLUMN 803 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 804 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 805 return 1; 806 } 807 #endif 808 pEList = pSelect->pEList; 809 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ 810 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 811 if( pItem->iCol ){ 812 if( pItem->iCol>pEList->nExpr ){ 813 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr); 814 return 1; 815 } 816 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType); 817 } 818 } 819 return 0; 820 } 821 822 /* 823 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. 824 ** The Name context of the SELECT statement is pNC. zType is either 825 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. 826 ** 827 ** This routine resolves each term of the clause into an expression. 828 ** If the order-by term is an integer I between 1 and N (where N is the 829 ** number of columns in the result set of the SELECT) then the expression 830 ** in the resolution is a copy of the I-th result-set expression. If 831 ** the order-by term is an identify that corresponds to the AS-name of 832 ** a result-set expression, then the term resolves to a copy of the 833 ** result-set expression. Otherwise, the expression is resolved in 834 ** the usual way - using sqlite3ResolveExprNames(). 835 ** 836 ** This routine returns the number of errors. If errors occur, then 837 ** an appropriate error message might be left in pParse. (OOM errors 838 ** excepted.) 839 */ 840 static int resolveOrderGroupBy( 841 NameContext *pNC, /* The name context of the SELECT statement */ 842 Select *pSelect, /* The SELECT statement holding pOrderBy */ 843 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ 844 const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 845 ){ 846 int i; /* Loop counter */ 847 int iCol; /* Column number */ 848 struct ExprList_item *pItem; /* A term of the ORDER BY clause */ 849 Parse *pParse; /* Parsing context */ 850 int nResult; /* Number of terms in the result set */ 851 852 if( pOrderBy==0 ) return 0; 853 nResult = pSelect->pEList->nExpr; 854 pParse = pNC->pParse; 855 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 856 Expr *pE = pItem->pExpr; 857 iCol = resolveAsName(pParse, pSelect->pEList, pE); 858 if( iCol<0 ){ 859 return 1; /* OOM error */ 860 } 861 if( iCol>0 ){ 862 /* If an AS-name match is found, mark this ORDER BY column as being 863 ** a copy of the iCol-th result-set column. The subsequent call to 864 ** sqlite3ResolveOrderGroupBy() will convert the expression to a 865 ** copy of the iCol-th result-set expression. */ 866 pItem->iCol = (u16)iCol; 867 continue; 868 } 869 if( sqlite3ExprIsInteger(pE, &iCol) ){ 870 /* The ORDER BY term is an integer constant. Again, set the column 871 ** number so that sqlite3ResolveOrderGroupBy() will convert the 872 ** order-by term to a copy of the result-set expression */ 873 if( iCol<1 ){ 874 resolveOutOfRangeError(pParse, zType, i+1, nResult); 875 return 1; 876 } 877 pItem->iCol = (u16)iCol; 878 continue; 879 } 880 881 /* Otherwise, treat the ORDER BY term as an ordinary expression */ 882 pItem->iCol = 0; 883 if( sqlite3ResolveExprNames(pNC, pE) ){ 884 return 1; 885 } 886 } 887 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); 888 } 889 890 /* 891 ** Resolve names in the SELECT statement p and all of its descendents. 892 */ 893 static int resolveSelectStep(Walker *pWalker, Select *p){ 894 NameContext *pOuterNC; /* Context that contains this SELECT */ 895 NameContext sNC; /* Name context of this SELECT */ 896 int isCompound; /* True if p is a compound select */ 897 int nCompound; /* Number of compound terms processed so far */ 898 Parse *pParse; /* Parsing context */ 899 ExprList *pEList; /* Result set expression list */ 900 int i; /* Loop counter */ 901 ExprList *pGroupBy; /* The GROUP BY clause */ 902 Select *pLeftmost; /* Left-most of SELECT of a compound */ 903 sqlite3 *db; /* Database connection */ 904 905 906 assert( p!=0 ); 907 if( p->selFlags & SF_Resolved ){ 908 return WRC_Prune; 909 } 910 pOuterNC = pWalker->u.pNC; 911 pParse = pWalker->pParse; 912 db = pParse->db; 913 914 /* Normally sqlite3SelectExpand() will be called first and will have 915 ** already expanded this SELECT. However, if this is a subquery within 916 ** an expression, sqlite3ResolveExprNames() will be called without a 917 ** prior call to sqlite3SelectExpand(). When that happens, let 918 ** sqlite3SelectPrep() do all of the processing for this SELECT. 919 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and 920 ** this routine in the correct order. 921 */ 922 if( (p->selFlags & SF_Expanded)==0 ){ 923 sqlite3SelectPrep(pParse, p, pOuterNC); 924 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; 925 } 926 927 isCompound = p->pPrior!=0; 928 nCompound = 0; 929 pLeftmost = p; 930 while( p ){ 931 assert( (p->selFlags & SF_Expanded)!=0 ); 932 assert( (p->selFlags & SF_Resolved)==0 ); 933 p->selFlags |= SF_Resolved; 934 935 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 936 ** are not allowed to refer to any names, so pass an empty NameContext. 937 */ 938 memset(&sNC, 0, sizeof(sNC)); 939 sNC.pParse = pParse; 940 if( sqlite3ResolveExprNames(&sNC, p->pLimit) || 941 sqlite3ResolveExprNames(&sNC, p->pOffset) ){ 942 return WRC_Abort; 943 } 944 945 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to 946 ** resolve the result-set expression list. 947 */ 948 sNC.allowAgg = 1; 949 sNC.pSrcList = p->pSrc; 950 sNC.pNext = pOuterNC; 951 952 /* Resolve names in the result set. */ 953 pEList = p->pEList; 954 assert( pEList!=0 ); 955 for(i=0; i<pEList->nExpr; i++){ 956 Expr *pX = pEList->a[i].pExpr; 957 if( sqlite3ResolveExprNames(&sNC, pX) ){ 958 return WRC_Abort; 959 } 960 } 961 962 /* Recursively resolve names in all subqueries 963 */ 964 for(i=0; i<p->pSrc->nSrc; i++){ 965 struct SrcList_item *pItem = &p->pSrc->a[i]; 966 if( pItem->pSelect ){ 967 const char *zSavedContext = pParse->zAuthContext; 968 if( pItem->zName ) pParse->zAuthContext = pItem->zName; 969 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); 970 pParse->zAuthContext = zSavedContext; 971 if( pParse->nErr || db->mallocFailed ) return WRC_Abort; 972 } 973 } 974 975 /* If there are no aggregate functions in the result-set, and no GROUP BY 976 ** expression, do not allow aggregates in any of the other expressions. 977 */ 978 assert( (p->selFlags & SF_Aggregate)==0 ); 979 pGroupBy = p->pGroupBy; 980 if( pGroupBy || sNC.hasAgg ){ 981 p->selFlags |= SF_Aggregate; 982 }else{ 983 sNC.allowAgg = 0; 984 } 985 986 /* If a HAVING clause is present, then there must be a GROUP BY clause. 987 */ 988 if( p->pHaving && !pGroupBy ){ 989 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 990 return WRC_Abort; 991 } 992 993 /* Add the expression list to the name-context before parsing the 994 ** other expressions in the SELECT statement. This is so that 995 ** expressions in the WHERE clause (etc.) can refer to expressions by 996 ** aliases in the result set. 997 ** 998 ** Minor point: If this is the case, then the expression will be 999 ** re-evaluated for each reference to it. 1000 */ 1001 sNC.pEList = p->pEList; 1002 if( sqlite3ResolveExprNames(&sNC, p->pWhere) || 1003 sqlite3ResolveExprNames(&sNC, p->pHaving) 1004 ){ 1005 return WRC_Abort; 1006 } 1007 1008 /* The ORDER BY and GROUP BY clauses may not refer to terms in 1009 ** outer queries 1010 */ 1011 sNC.pNext = 0; 1012 sNC.allowAgg = 1; 1013 1014 /* Process the ORDER BY clause for singleton SELECT statements. 1015 ** The ORDER BY clause for compounds SELECT statements is handled 1016 ** below, after all of the result-sets for all of the elements of 1017 ** the compound have been resolved. 1018 */ 1019 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){ 1020 return WRC_Abort; 1021 } 1022 if( db->mallocFailed ){ 1023 return WRC_Abort; 1024 } 1025 1026 /* Resolve the GROUP BY clause. At the same time, make sure 1027 ** the GROUP BY clause does not contain aggregate functions. 1028 */ 1029 if( pGroupBy ){ 1030 struct ExprList_item *pItem; 1031 1032 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ 1033 return WRC_Abort; 1034 } 1035 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 1036 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 1037 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 1038 "the GROUP BY clause"); 1039 return WRC_Abort; 1040 } 1041 } 1042 } 1043 1044 /* Advance to the next term of the compound 1045 */ 1046 p = p->pPrior; 1047 nCompound++; 1048 } 1049 1050 /* Resolve the ORDER BY on a compound SELECT after all terms of 1051 ** the compound have been resolved. 1052 */ 1053 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ 1054 return WRC_Abort; 1055 } 1056 1057 return WRC_Prune; 1058 } 1059 1060 /* 1061 ** This routine walks an expression tree and resolves references to 1062 ** table columns and result-set columns. At the same time, do error 1063 ** checking on function usage and set a flag if any aggregate functions 1064 ** are seen. 1065 ** 1066 ** To resolve table columns references we look for nodes (or subtrees) of the 1067 ** form X.Y.Z or Y.Z or just Z where 1068 ** 1069 ** X: The name of a database. Ex: "main" or "temp" or 1070 ** the symbolic name assigned to an ATTACH-ed database. 1071 ** 1072 ** Y: The name of a table in a FROM clause. Or in a trigger 1073 ** one of the special names "old" or "new". 1074 ** 1075 ** Z: The name of a column in table Y. 1076 ** 1077 ** The node at the root of the subtree is modified as follows: 1078 ** 1079 ** Expr.op Changed to TK_COLUMN 1080 ** Expr.pTab Points to the Table object for X.Y 1081 ** Expr.iColumn The column index in X.Y. -1 for the rowid. 1082 ** Expr.iTable The VDBE cursor number for X.Y 1083 ** 1084 ** 1085 ** To resolve result-set references, look for expression nodes of the 1086 ** form Z (with no X and Y prefix) where the Z matches the right-hand 1087 ** size of an AS clause in the result-set of a SELECT. The Z expression 1088 ** is replaced by a copy of the left-hand side of the result-set expression. 1089 ** Table-name and function resolution occurs on the substituted expression 1090 ** tree. For example, in: 1091 ** 1092 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; 1093 ** 1094 ** The "x" term of the order by is replaced by "a+b" to render: 1095 ** 1096 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; 1097 ** 1098 ** Function calls are checked to make sure that the function is 1099 ** defined and that the correct number of arguments are specified. 1100 ** If the function is an aggregate function, then the pNC->hasAgg is 1101 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. 1102 ** If an expression contains aggregate functions then the EP_Agg 1103 ** property on the expression is set. 1104 ** 1105 ** An error message is left in pParse if anything is amiss. The number 1106 ** if errors is returned. 1107 */ 1108 int sqlite3ResolveExprNames( 1109 NameContext *pNC, /* Namespace to resolve expressions in. */ 1110 Expr *pExpr /* The expression to be analyzed. */ 1111 ){ 1112 int savedHasAgg; 1113 Walker w; 1114 1115 if( pExpr==0 ) return 0; 1116 #if SQLITE_MAX_EXPR_DEPTH>0 1117 { 1118 Parse *pParse = pNC->pParse; 1119 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){ 1120 return 1; 1121 } 1122 pParse->nHeight += pExpr->nHeight; 1123 } 1124 #endif 1125 savedHasAgg = pNC->hasAgg; 1126 pNC->hasAgg = 0; 1127 w.xExprCallback = resolveExprStep; 1128 w.xSelectCallback = resolveSelectStep; 1129 w.pParse = pNC->pParse; 1130 w.u.pNC = pNC; 1131 sqlite3WalkExpr(&w, pExpr); 1132 #if SQLITE_MAX_EXPR_DEPTH>0 1133 pNC->pParse->nHeight -= pExpr->nHeight; 1134 #endif 1135 if( pNC->nErr>0 ){ 1136 ExprSetProperty(pExpr, EP_Error); 1137 } 1138 if( pNC->hasAgg ){ 1139 ExprSetProperty(pExpr, EP_Agg); 1140 }else if( savedHasAgg ){ 1141 pNC->hasAgg = 1; 1142 } 1143 return ExprHasProperty(pExpr, EP_Error); 1144 } 1145 1146 1147 /* 1148 ** Resolve all names in all expressions of a SELECT and in all 1149 ** decendents of the SELECT, including compounds off of p->pPrior, 1150 ** subqueries in expressions, and subqueries used as FROM clause 1151 ** terms. 1152 ** 1153 ** See sqlite3ResolveExprNames() for a description of the kinds of 1154 ** transformations that occur. 1155 ** 1156 ** All SELECT statements should have been expanded using 1157 ** sqlite3SelectExpand() prior to invoking this routine. 1158 */ 1159 void sqlite3ResolveSelectNames( 1160 Parse *pParse, /* The parser context */ 1161 Select *p, /* The SELECT statement being coded. */ 1162 NameContext *pOuterNC /* Name context for parent SELECT statement */ 1163 ){ 1164 Walker w; 1165 1166 assert( p!=0 ); 1167 w.xExprCallback = resolveExprStep; 1168 w.xSelectCallback = resolveSelectStep; 1169 w.pParse = pParse; 1170 w.u.pNC = pOuterNC; 1171 sqlite3WalkSelect(&w, p); 1172 } 1173