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