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