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 #include "sqliteInt.h" 18 19 /* 20 ** Walk the expression tree pExpr and increase the aggregate function 21 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node. 22 ** This needs to occur when copying a TK_AGG_FUNCTION node from an 23 ** outer query into an inner subquery. 24 ** 25 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..) 26 ** is a helper function - a callback for the tree walker. 27 */ 28 static int incrAggDepth(Walker *pWalker, Expr *pExpr){ 29 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n; 30 return WRC_Continue; 31 } 32 static void incrAggFunctionDepth(Expr *pExpr, int N){ 33 if( N>0 ){ 34 Walker w; 35 memset(&w, 0, sizeof(w)); 36 w.xExprCallback = incrAggDepth; 37 w.u.n = N; 38 sqlite3WalkExpr(&w, pExpr); 39 } 40 } 41 42 /* 43 ** Turn the pExpr expression into an alias for the iCol-th column of the 44 ** result set in pEList. 45 ** 46 ** If the reference is followed by a COLLATE operator, then make sure 47 ** the COLLATE operator is preserved. For example: 48 ** 49 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase; 50 ** 51 ** Should be transformed into: 52 ** 53 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase; 54 ** 55 ** The nSubquery parameter specifies how many levels of subquery the 56 ** alias is removed from the original expression. The usual value is 57 ** zero but it might be more if the alias is contained within a subquery 58 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION 59 ** structures must be increased by the nSubquery amount. 60 */ 61 static void resolveAlias( 62 Parse *pParse, /* Parsing context */ 63 ExprList *pEList, /* A result set */ 64 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ 65 Expr *pExpr, /* Transform this into an alias to the result set */ 66 const char *zType, /* "GROUP" or "ORDER" or "" */ 67 int nSubquery /* Number of subqueries that the label is moving */ 68 ){ 69 Expr *pOrig; /* The iCol-th column of the result set */ 70 Expr *pDup; /* Copy of pOrig */ 71 sqlite3 *db; /* The database connection */ 72 73 assert( iCol>=0 && iCol<pEList->nExpr ); 74 pOrig = pEList->a[iCol].pExpr; 75 assert( pOrig!=0 ); 76 db = pParse->db; 77 pDup = sqlite3ExprDup(db, pOrig, 0); 78 if( pDup!=0 ){ 79 if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery); 80 if( pExpr->op==TK_COLLATE ){ 81 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); 82 } 83 84 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 85 ** prevents ExprDelete() from deleting the Expr structure itself, 86 ** allowing it to be repopulated by the memcpy() on the following line. 87 ** The pExpr->u.zToken might point into memory that will be freed by the 88 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to 89 ** make a copy of the token before doing the sqlite3DbFree(). 90 */ 91 ExprSetProperty(pExpr, EP_Static); 92 sqlite3ExprDelete(db, pExpr); 93 memcpy(pExpr, pDup, sizeof(*pExpr)); 94 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ 95 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); 96 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); 97 pExpr->flags |= EP_MemToken; 98 } 99 sqlite3DbFree(db, pDup); 100 } 101 ExprSetProperty(pExpr, EP_Alias); 102 } 103 104 105 /* 106 ** Return TRUE if the name zCol occurs anywhere in the USING clause. 107 ** 108 ** Return FALSE if the USING clause is NULL or if it does not contain 109 ** zCol. 110 */ 111 static int nameInUsingClause(IdList *pUsing, const char *zCol){ 112 if( pUsing ){ 113 int k; 114 for(k=0; k<pUsing->nId; k++){ 115 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; 116 } 117 } 118 return 0; 119 } 120 121 /* 122 ** Subqueries stores the original database, table and column names for their 123 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN". 124 ** Check to see if the zSpan given to this routine matches the zDb, zTab, 125 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will 126 ** match anything. 127 */ 128 int sqlite3MatchSpanName( 129 const char *zSpan, 130 const char *zCol, 131 const char *zTab, 132 const char *zDb 133 ){ 134 int n; 135 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} 136 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ 137 return 0; 138 } 139 zSpan += n+1; 140 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} 141 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ 142 return 0; 143 } 144 zSpan += n+1; 145 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){ 146 return 0; 147 } 148 return 1; 149 } 150 151 /* 152 ** Return TRUE if the double-quoted string mis-feature should be supported. 153 */ 154 static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){ 155 if( db->init.busy ) return 1; /* Always support for legacy schemas */ 156 if( pTopNC->ncFlags & NC_IsDDL ){ 157 /* Currently parsing a DDL statement */ 158 if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){ 159 return 1; 160 } 161 return (db->flags & SQLITE_DqsDDL)!=0; 162 }else{ 163 /* Currently parsing a DML statement */ 164 return (db->flags & SQLITE_DqsDML)!=0; 165 } 166 } 167 168 /* 169 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up 170 ** that name in the set of source tables in pSrcList and make the pExpr 171 ** expression node refer back to that source column. The following changes 172 ** are made to pExpr: 173 ** 174 ** pExpr->iDb Set the index in db->aDb[] of the database X 175 ** (even if X is implied). 176 ** pExpr->iTable Set to the cursor number for the table obtained 177 ** from pSrcList. 178 ** pExpr->y.pTab Points to the Table structure of X.Y (even if 179 ** X and/or Y are implied.) 180 ** pExpr->iColumn Set to the column number within the table. 181 ** pExpr->op Set to TK_COLUMN. 182 ** pExpr->pLeft Any expression this points to is deleted 183 ** pExpr->pRight Any expression this points to is deleted. 184 ** 185 ** The zDb variable is the name of the database (the "X"). This value may be 186 ** NULL meaning that name is of the form Y.Z or Z. Any available database 187 ** can be used. The zTable variable is the name of the table (the "Y"). This 188 ** value can be NULL if zDb is also NULL. If zTable is NULL it 189 ** means that the form of the name is Z and that columns from any table 190 ** can be used. 191 ** 192 ** If the name cannot be resolved unambiguously, leave an error message 193 ** in pParse and return WRC_Abort. Return WRC_Prune on success. 194 */ 195 static int lookupName( 196 Parse *pParse, /* The parsing context */ 197 const char *zDb, /* Name of the database containing table, or NULL */ 198 const char *zTab, /* Name of table containing column, or NULL */ 199 const char *zCol, /* Name of the column. */ 200 NameContext *pNC, /* The name context used to resolve the name */ 201 Expr *pExpr /* Make this EXPR node point to the selected column */ 202 ){ 203 int i, j; /* Loop counters */ 204 int cnt = 0; /* Number of matching column names */ 205 int cntTab = 0; /* Number of matching table names */ 206 int nSubquery = 0; /* How many levels of subquery */ 207 sqlite3 *db = pParse->db; /* The database connection */ 208 struct SrcList_item *pItem; /* Use for looping over pSrcList items */ 209 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ 210 NameContext *pTopNC = pNC; /* First namecontext in the list */ 211 Schema *pSchema = 0; /* Schema of the expression */ 212 int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ 213 Table *pTab = 0; /* Table hold the row */ 214 Column *pCol; /* A column of pTab */ 215 216 assert( pNC ); /* the name context cannot be NULL. */ 217 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ 218 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 219 220 /* Initialize the node to no-match */ 221 pExpr->iTable = -1; 222 ExprSetVVAProperty(pExpr, EP_NoReduce); 223 224 /* Translate the schema name in zDb into a pointer to the corresponding 225 ** schema. If not found, pSchema will remain NULL and nothing will match 226 ** resulting in an appropriate error message toward the end of this routine 227 */ 228 if( zDb ){ 229 testcase( pNC->ncFlags & NC_PartIdx ); 230 testcase( pNC->ncFlags & NC_IsCheck ); 231 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ 232 /* Silently ignore database qualifiers inside CHECK constraints and 233 ** partial indices. Do not raise errors because that might break 234 ** legacy and because it does not hurt anything to just ignore the 235 ** database name. */ 236 zDb = 0; 237 }else{ 238 for(i=0; i<db->nDb; i++){ 239 assert( db->aDb[i].zDbSName ); 240 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ 241 pSchema = db->aDb[i].pSchema; 242 break; 243 } 244 } 245 } 246 } 247 248 /* Start at the inner-most context and move outward until a match is found */ 249 assert( pNC && cnt==0 ); 250 do{ 251 ExprList *pEList; 252 SrcList *pSrcList = pNC->pSrcList; 253 254 if( pSrcList ){ 255 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ 256 pTab = pItem->pTab; 257 assert( pTab!=0 && pTab->zName!=0 ); 258 assert( pTab->nCol>0 ); 259 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ 260 int hit = 0; 261 pEList = pItem->pSelect->pEList; 262 for(j=0; j<pEList->nExpr; j++){ 263 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ 264 cnt++; 265 cntTab = 2; 266 pMatch = pItem; 267 pExpr->iColumn = j; 268 hit = 1; 269 } 270 } 271 if( hit || zTab==0 ) continue; 272 } 273 if( zDb && pTab->pSchema!=pSchema ){ 274 continue; 275 } 276 if( zTab ){ 277 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; 278 assert( zTabName!=0 ); 279 if( sqlite3StrICmp(zTabName, zTab)!=0 ){ 280 continue; 281 } 282 if( IN_RENAME_OBJECT && pItem->zAlias ){ 283 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); 284 } 285 } 286 if( 0==(cntTab++) ){ 287 pMatch = pItem; 288 } 289 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ 290 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ 291 /* If there has been exactly one prior match and this match 292 ** is for the right-hand table of a NATURAL JOIN or is in a 293 ** USING clause, then skip this match. 294 */ 295 if( cnt==1 ){ 296 if( pItem->fg.jointype & JT_NATURAL ) continue; 297 if( nameInUsingClause(pItem->pUsing, zCol) ) continue; 298 } 299 cnt++; 300 pMatch = pItem; 301 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ 302 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; 303 break; 304 } 305 } 306 } 307 if( pMatch ){ 308 pExpr->iTable = pMatch->iCursor; 309 pExpr->y.pTab = pMatch->pTab; 310 /* RIGHT JOIN not (yet) supported */ 311 assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); 312 if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ 313 ExprSetProperty(pExpr, EP_CanBeNull); 314 } 315 pSchema = pExpr->y.pTab->pSchema; 316 } 317 } /* if( pSrcList ) */ 318 319 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) 320 /* If we have not already resolved the name, then maybe 321 ** it is a new.* or old.* trigger argument reference. Or 322 ** maybe it is an excluded.* from an upsert. 323 */ 324 if( zDb==0 && zTab!=0 && cntTab==0 ){ 325 pTab = 0; 326 #ifndef SQLITE_OMIT_TRIGGER 327 if( pParse->pTriggerTab!=0 ){ 328 int op = pParse->eTriggerOp; 329 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); 330 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ 331 pExpr->iTable = 1; 332 pTab = pParse->pTriggerTab; 333 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ 334 pExpr->iTable = 0; 335 pTab = pParse->pTriggerTab; 336 } 337 } 338 #endif /* SQLITE_OMIT_TRIGGER */ 339 #ifndef SQLITE_OMIT_UPSERT 340 if( (pNC->ncFlags & NC_UUpsert)!=0 ){ 341 Upsert *pUpsert = pNC->uNC.pUpsert; 342 if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){ 343 pTab = pUpsert->pUpsertSrc->a[0].pTab; 344 pExpr->iTable = 2; 345 } 346 } 347 #endif /* SQLITE_OMIT_UPSERT */ 348 349 if( pTab ){ 350 int iCol; 351 pSchema = pTab->pSchema; 352 cntTab++; 353 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ 354 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ 355 if( iCol==pTab->iPKey ){ 356 iCol = -1; 357 } 358 break; 359 } 360 } 361 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ 362 /* IMP: R-51414-32910 */ 363 iCol = -1; 364 } 365 if( iCol<pTab->nCol ){ 366 cnt++; 367 #ifndef SQLITE_OMIT_UPSERT 368 if( pExpr->iTable==2 ){ 369 testcase( iCol==(-1) ); 370 if( IN_RENAME_OBJECT ){ 371 pExpr->iColumn = iCol; 372 pExpr->y.pTab = pTab; 373 eNewExprOp = TK_COLUMN; 374 }else{ 375 pExpr->iTable = pNC->uNC.pUpsert->regData + iCol; 376 eNewExprOp = TK_REGISTER; 377 ExprSetProperty(pExpr, EP_Alias); 378 } 379 }else 380 #endif /* SQLITE_OMIT_UPSERT */ 381 { 382 #ifndef SQLITE_OMIT_TRIGGER 383 if( iCol<0 ){ 384 pExpr->affExpr = SQLITE_AFF_INTEGER; 385 }else if( pExpr->iTable==0 ){ 386 testcase( iCol==31 ); 387 testcase( iCol==32 ); 388 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); 389 }else{ 390 testcase( iCol==31 ); 391 testcase( iCol==32 ); 392 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); 393 } 394 pExpr->y.pTab = pTab; 395 pExpr->iColumn = (i16)iCol; 396 eNewExprOp = TK_TRIGGER; 397 #endif /* SQLITE_OMIT_TRIGGER */ 398 } 399 } 400 } 401 } 402 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ 403 404 /* 405 ** Perhaps the name is a reference to the ROWID 406 */ 407 if( cnt==0 408 && cntTab==1 409 && pMatch 410 && (pNC->ncFlags & NC_IdxExpr)==0 411 && sqlite3IsRowid(zCol) 412 && VisibleRowid(pMatch->pTab) 413 ){ 414 cnt = 1; 415 pExpr->iColumn = -1; 416 pExpr->affExpr = SQLITE_AFF_INTEGER; 417 } 418 419 /* 420 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z 421 ** might refer to an result-set alias. This happens, for example, when 422 ** we are resolving names in the WHERE clause of the following command: 423 ** 424 ** SELECT a+b AS x FROM table WHERE x<10; 425 ** 426 ** In cases like this, replace pExpr with a copy of the expression that 427 ** forms the result set entry ("a+b" in the example) and return immediately. 428 ** Note that the expression in the result set should have already been 429 ** resolved by the time the WHERE clause is resolved. 430 ** 431 ** The ability to use an output result-set column in the WHERE, GROUP BY, 432 ** or HAVING clauses, or as part of a larger expression in the ORDER BY 433 ** clause is not standard SQL. This is a (goofy) SQLite extension, that 434 ** is supported for backwards compatibility only. Hence, we issue a warning 435 ** on sqlite3_log() whenever the capability is used. 436 */ 437 if( (pNC->ncFlags & NC_UEList)!=0 438 && cnt==0 439 && zTab==0 440 ){ 441 pEList = pNC->uNC.pEList; 442 assert( pEList!=0 ); 443 for(j=0; j<pEList->nExpr; j++){ 444 char *zAs = pEList->a[j].zName; 445 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 446 Expr *pOrig; 447 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 448 assert( pExpr->x.pList==0 ); 449 assert( pExpr->x.pSelect==0 ); 450 pOrig = pEList->a[j].pExpr; 451 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ 452 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); 453 return WRC_Abort; 454 } 455 if( (pNC->ncFlags&NC_AllowWin)==0 && ExprHasProperty(pOrig, EP_Win) ){ 456 sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs); 457 return WRC_Abort; 458 } 459 if( sqlite3ExprVectorSize(pOrig)!=1 ){ 460 sqlite3ErrorMsg(pParse, "row value misused"); 461 return WRC_Abort; 462 } 463 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); 464 cnt = 1; 465 pMatch = 0; 466 assert( zTab==0 && zDb==0 ); 467 if( IN_RENAME_OBJECT ){ 468 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); 469 } 470 goto lookupname_end; 471 } 472 } 473 } 474 475 /* Advance to the next name context. The loop will exit when either 476 ** we have a match (cnt>0) or when we run out of name contexts. 477 */ 478 if( cnt ) break; 479 pNC = pNC->pNext; 480 nSubquery++; 481 }while( pNC ); 482 483 484 /* 485 ** If X and Y are NULL (in other words if only the column name Z is 486 ** supplied) and the value of Z is enclosed in double-quotes, then 487 ** Z is a string literal if it doesn't match any column names. In that 488 ** case, we need to return right away and not make any changes to 489 ** pExpr. 490 ** 491 ** Because no reference was made to outer contexts, the pNC->nRef 492 ** fields are not changed in any context. 493 */ 494 if( cnt==0 && zTab==0 ){ 495 assert( pExpr->op==TK_ID ); 496 if( ExprHasProperty(pExpr,EP_DblQuoted) 497 && areDoubleQuotedStringsEnabled(db, pTopNC) 498 ){ 499 /* If a double-quoted identifier does not match any known column name, 500 ** then treat it as a string. 501 ** 502 ** This hack was added in the early days of SQLite in a misguided attempt 503 ** to be compatible with MySQL 3.x, which used double-quotes for strings. 504 ** I now sorely regret putting in this hack. The effect of this hack is 505 ** that misspelled identifier names are silently converted into strings 506 ** rather than causing an error, to the frustration of countless 507 ** programmers. To all those frustrated programmers, my apologies. 508 ** 509 ** Someday, I hope to get rid of this hack. Unfortunately there is 510 ** a huge amount of legacy SQL that uses it. So for now, we just 511 ** issue a warning. 512 */ 513 sqlite3_log(SQLITE_WARNING, 514 "double-quoted string literal: \"%w\"", zCol); 515 #ifdef SQLITE_ENABLE_NORMALIZE 516 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); 517 #endif 518 pExpr->op = TK_STRING; 519 pExpr->y.pTab = 0; 520 return WRC_Prune; 521 } 522 if( sqlite3ExprIdToTrueFalse(pExpr) ){ 523 return WRC_Prune; 524 } 525 } 526 527 /* 528 ** cnt==0 means there was not match. cnt>1 means there were two or 529 ** more matches. Either way, we have an error. 530 */ 531 if( cnt!=1 ){ 532 const char *zErr; 533 zErr = cnt==0 ? "no such column" : "ambiguous column name"; 534 if( zDb ){ 535 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); 536 }else if( zTab ){ 537 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); 538 }else{ 539 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); 540 } 541 pParse->checkSchema = 1; 542 pTopNC->nErr++; 543 } 544 545 /* If a column from a table in pSrcList is referenced, then record 546 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes 547 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the 548 ** column number is greater than the number of bits in the bitmask 549 ** then set the high-order bit of the bitmask. 550 */ 551 if( pExpr->iColumn>=0 && pMatch!=0 ){ 552 int n = pExpr->iColumn; 553 testcase( n==BMS-1 ); 554 if( n>=BMS ){ 555 n = BMS-1; 556 } 557 assert( pMatch->iCursor==pExpr->iTable ); 558 pMatch->colUsed |= ((Bitmask)1)<<n; 559 } 560 561 /* Clean up and return 562 */ 563 sqlite3ExprDelete(db, pExpr->pLeft); 564 pExpr->pLeft = 0; 565 sqlite3ExprDelete(db, pExpr->pRight); 566 pExpr->pRight = 0; 567 pExpr->op = eNewExprOp; 568 ExprSetProperty(pExpr, EP_Leaf); 569 lookupname_end: 570 if( cnt==1 ){ 571 assert( pNC!=0 ); 572 if( !ExprHasProperty(pExpr, EP_Alias) ){ 573 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); 574 } 575 /* Increment the nRef value on all name contexts from TopNC up to 576 ** the point where the name matched. */ 577 for(;;){ 578 assert( pTopNC!=0 ); 579 pTopNC->nRef++; 580 if( pTopNC==pNC ) break; 581 pTopNC = pTopNC->pNext; 582 } 583 return WRC_Prune; 584 } else { 585 return WRC_Abort; 586 } 587 } 588 589 /* 590 ** Allocate and return a pointer to an expression to load the column iCol 591 ** from datasource iSrc in SrcList pSrc. 592 */ 593 Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ 594 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); 595 if( p ){ 596 struct SrcList_item *pItem = &pSrc->a[iSrc]; 597 p->y.pTab = pItem->pTab; 598 p->iTable = pItem->iCursor; 599 if( p->y.pTab->iPKey==iCol ){ 600 p->iColumn = -1; 601 }else{ 602 p->iColumn = (ynVar)iCol; 603 testcase( iCol==BMS ); 604 testcase( iCol==BMS-1 ); 605 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); 606 } 607 } 608 return p; 609 } 610 611 /* 612 ** Report an error that an expression is not valid for some set of 613 ** pNC->ncFlags values determined by validMask. 614 */ 615 static void notValid( 616 Parse *pParse, /* Leave error message here */ 617 NameContext *pNC, /* The name context */ 618 const char *zMsg, /* Type of error */ 619 int validMask /* Set of contexts for which prohibited */ 620 ){ 621 assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 ); 622 if( (pNC->ncFlags & validMask)!=0 ){ 623 const char *zIn = "partial index WHERE clauses"; 624 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions"; 625 #ifndef SQLITE_OMIT_CHECK 626 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints"; 627 #endif 628 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); 629 } 630 } 631 632 /* 633 ** Expression p should encode a floating point value between 1.0 and 0.0. 634 ** Return 1024 times this value. Or return -1 if p is not a floating point 635 ** value between 1.0 and 0.0. 636 */ 637 static int exprProbability(Expr *p){ 638 double r = -1.0; 639 if( p->op!=TK_FLOAT ) return -1; 640 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); 641 assert( r>=0.0 ); 642 if( r>1.0 ) return -1; 643 return (int)(r*134217728.0); 644 } 645 646 /* 647 ** This routine is callback for sqlite3WalkExpr(). 648 ** 649 ** Resolve symbolic names into TK_COLUMN operators for the current 650 ** node in the expression tree. Return 0 to continue the search down 651 ** the tree or 2 to abort the tree walk. 652 ** 653 ** This routine also does error checking and name resolution for 654 ** function names. The operator for aggregate functions is changed 655 ** to TK_AGG_FUNCTION. 656 */ 657 static int resolveExprStep(Walker *pWalker, Expr *pExpr){ 658 NameContext *pNC; 659 Parse *pParse; 660 661 pNC = pWalker->u.pNC; 662 assert( pNC!=0 ); 663 pParse = pNC->pParse; 664 assert( pParse==pWalker->pParse ); 665 666 #ifndef NDEBUG 667 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ 668 SrcList *pSrcList = pNC->pSrcList; 669 int i; 670 for(i=0; i<pNC->pSrcList->nSrc; i++){ 671 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab); 672 } 673 } 674 #endif 675 switch( pExpr->op ){ 676 677 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) 678 /* The special operator TK_ROW means use the rowid for the first 679 ** column in the FROM clause. This is used by the LIMIT and ORDER BY 680 ** clause processing on UPDATE and DELETE statements. 681 */ 682 case TK_ROW: { 683 SrcList *pSrcList = pNC->pSrcList; 684 struct SrcList_item *pItem; 685 assert( pSrcList && pSrcList->nSrc==1 ); 686 pItem = pSrcList->a; 687 assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 ); 688 pExpr->op = TK_COLUMN; 689 pExpr->y.pTab = pItem->pTab; 690 pExpr->iTable = pItem->iCursor; 691 pExpr->iColumn = -1; 692 pExpr->affExpr = SQLITE_AFF_INTEGER; 693 break; 694 } 695 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) 696 && !defined(SQLITE_OMIT_SUBQUERY) */ 697 698 /* A column name: ID 699 ** Or table name and column name: ID.ID 700 ** Or a database, table and column: ID.ID.ID 701 ** 702 ** The TK_ID and TK_OUT cases are combined so that there will only 703 ** be one call to lookupName(). Then the compiler will in-line 704 ** lookupName() for a size reduction and performance increase. 705 */ 706 case TK_ID: 707 case TK_DOT: { 708 const char *zColumn; 709 const char *zTable; 710 const char *zDb; 711 Expr *pRight; 712 713 if( pExpr->op==TK_ID ){ 714 zDb = 0; 715 zTable = 0; 716 zColumn = pExpr->u.zToken; 717 }else{ 718 Expr *pLeft = pExpr->pLeft; 719 notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr); 720 pRight = pExpr->pRight; 721 if( pRight->op==TK_ID ){ 722 zDb = 0; 723 }else{ 724 assert( pRight->op==TK_DOT ); 725 zDb = pLeft->u.zToken; 726 pLeft = pRight->pLeft; 727 pRight = pRight->pRight; 728 } 729 zTable = pLeft->u.zToken; 730 zColumn = pRight->u.zToken; 731 if( IN_RENAME_OBJECT ){ 732 sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight); 733 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft); 734 } 735 } 736 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); 737 } 738 739 /* Resolve function names 740 */ 741 case TK_FUNCTION: { 742 ExprList *pList = pExpr->x.pList; /* The argument list */ 743 int n = pList ? pList->nExpr : 0; /* Number of arguments */ 744 int no_such_func = 0; /* True if no such function exists */ 745 int wrong_num_args = 0; /* True if wrong number of arguments */ 746 int is_agg = 0; /* True if is an aggregate function */ 747 int nId; /* Number of characters in function name */ 748 const char *zId; /* The function name. */ 749 FuncDef *pDef; /* Information about the function */ 750 u8 enc = ENC(pParse->db); /* The database encoding */ 751 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin)); 752 #ifndef SQLITE_OMIT_WINDOWFUNC 753 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0); 754 #endif 755 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 756 zId = pExpr->u.zToken; 757 nId = sqlite3Strlen30(zId); 758 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0); 759 if( pDef==0 ){ 760 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0); 761 if( pDef==0 ){ 762 no_such_func = 1; 763 }else{ 764 wrong_num_args = 1; 765 } 766 }else{ 767 is_agg = pDef->xFinalize!=0; 768 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ 769 ExprSetProperty(pExpr, EP_Unlikely); 770 if( n==2 ){ 771 pExpr->iTable = exprProbability(pList->a[1].pExpr); 772 if( pExpr->iTable<0 ){ 773 sqlite3ErrorMsg(pParse, 774 "second argument to likelihood() must be a " 775 "constant between 0.0 and 1.0"); 776 pNC->nErr++; 777 } 778 }else{ 779 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is 780 ** equivalent to likelihood(X, 0.0625). 781 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is 782 ** short-hand for likelihood(X,0.0625). 783 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand 784 ** for likelihood(X,0.9375). 785 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent 786 ** to likelihood(X,0.9375). */ 787 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */ 788 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120; 789 } 790 } 791 #ifndef SQLITE_OMIT_AUTHORIZATION 792 { 793 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); 794 if( auth!=SQLITE_OK ){ 795 if( auth==SQLITE_DENY ){ 796 sqlite3ErrorMsg(pParse, "not authorized to use function: %s", 797 pDef->zName); 798 pNC->nErr++; 799 } 800 pExpr->op = TK_NULL; 801 return WRC_Prune; 802 } 803 } 804 #endif 805 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ 806 /* For the purposes of the EP_ConstFunc flag, date and time 807 ** functions and other functions that change slowly are considered 808 ** constant because they are constant for the duration of one query */ 809 ExprSetProperty(pExpr,EP_ConstFunc); 810 } 811 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ 812 /* Date/time functions that use 'now', and other functions like 813 ** sqlite_version() that might change over time cannot be used 814 ** in an index. */ 815 notValid(pParse, pNC, "non-deterministic functions", 816 NC_IdxExpr|NC_PartIdx); 817 } 818 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 819 && pParse->nested==0 820 && sqlite3Config.bInternalFunctions==0 821 ){ 822 /* Internal-use-only functions are disallowed unless the 823 ** SQL is being compiled using sqlite3NestedParse() */ 824 no_such_func = 1; 825 pDef = 0; 826 }else 827 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0 828 && ExprHasProperty(pExpr, EP_Indirect) 829 && !IN_RENAME_OBJECT 830 ){ 831 /* Functions tagged with SQLITE_DIRECTONLY may not be used 832 ** inside of triggers and views */ 833 sqlite3ErrorMsg(pParse, "%s() prohibited in triggers and views", 834 pDef->zName); 835 } 836 } 837 838 if( 0==IN_RENAME_OBJECT ){ 839 #ifndef SQLITE_OMIT_WINDOWFUNC 840 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX) 841 || (pDef->xValue==0 && pDef->xInverse==0) 842 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize) 843 ); 844 if( pDef && pDef->xValue==0 && pWin ){ 845 sqlite3ErrorMsg(pParse, 846 "%.*s() may not be used as a window function", nId, zId 847 ); 848 pNC->nErr++; 849 }else if( 850 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) 851 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin) 852 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0) 853 ){ 854 const char *zType; 855 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){ 856 zType = "window"; 857 }else{ 858 zType = "aggregate"; 859 } 860 sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId); 861 pNC->nErr++; 862 is_agg = 0; 863 } 864 #else 865 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){ 866 sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId); 867 pNC->nErr++; 868 is_agg = 0; 869 } 870 #endif 871 else if( no_such_func && pParse->db->init.busy==0 872 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 873 && pParse->explain==0 874 #endif 875 ){ 876 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); 877 pNC->nErr++; 878 }else if( wrong_num_args ){ 879 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", 880 nId, zId); 881 pNC->nErr++; 882 } 883 #ifndef SQLITE_OMIT_WINDOWFUNC 884 else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){ 885 sqlite3ErrorMsg(pParse, 886 "FILTER may not be used with non-aggregate %.*s()", 887 nId, zId 888 ); 889 pNC->nErr++; 890 } 891 #endif 892 if( is_agg ){ 893 /* Window functions may not be arguments of aggregate functions. 894 ** Or arguments of other window functions. But aggregate functions 895 ** may be arguments for window functions. */ 896 #ifndef SQLITE_OMIT_WINDOWFUNC 897 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0)); 898 #else 899 pNC->ncFlags &= ~NC_AllowAgg; 900 #endif 901 } 902 } 903 #ifndef SQLITE_OMIT_WINDOWFUNC 904 else if( ExprHasProperty(pExpr, EP_WinFunc) ){ 905 is_agg = 1; 906 } 907 #endif 908 sqlite3WalkExprList(pWalker, pList); 909 if( is_agg ){ 910 #ifndef SQLITE_OMIT_WINDOWFUNC 911 if( pWin ){ 912 Select *pSel = pNC->pWinSelect; 913 assert( pWin==pExpr->y.pWin ); 914 if( IN_RENAME_OBJECT==0 ){ 915 sqlite3WindowUpdate(pParse, pSel->pWinDefn, pWin, pDef); 916 } 917 sqlite3WalkExprList(pWalker, pWin->pPartition); 918 sqlite3WalkExprList(pWalker, pWin->pOrderBy); 919 sqlite3WalkExpr(pWalker, pWin->pFilter); 920 sqlite3WindowLink(pSel, pWin); 921 pNC->ncFlags |= NC_HasWin; 922 }else 923 #endif /* SQLITE_OMIT_WINDOWFUNC */ 924 { 925 NameContext *pNC2 = pNC; 926 pExpr->op = TK_AGG_FUNCTION; 927 pExpr->op2 = 0; 928 #ifndef SQLITE_OMIT_WINDOWFUNC 929 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 930 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter); 931 } 932 #endif 933 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ 934 pExpr->op2++; 935 pNC2 = pNC2->pNext; 936 } 937 assert( pDef!=0 || IN_RENAME_OBJECT ); 938 if( pNC2 && pDef ){ 939 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); 940 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); 941 pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); 942 943 } 944 } 945 pNC->ncFlags |= savedAllowFlags; 946 } 947 /* FIX ME: Compute pExpr->affinity based on the expected return 948 ** type of the function 949 */ 950 return WRC_Prune; 951 } 952 #ifndef SQLITE_OMIT_SUBQUERY 953 case TK_SELECT: 954 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); 955 #endif 956 case TK_IN: { 957 testcase( pExpr->op==TK_IN ); 958 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 959 int nRef = pNC->nRef; 960 notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr); 961 sqlite3WalkSelect(pWalker, pExpr->x.pSelect); 962 assert( pNC->nRef>=nRef ); 963 if( nRef!=pNC->nRef ){ 964 ExprSetProperty(pExpr, EP_VarSelect); 965 pNC->ncFlags |= NC_VarSelect; 966 } 967 } 968 break; 969 } 970 case TK_VARIABLE: { 971 notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr); 972 break; 973 } 974 case TK_IS: 975 case TK_ISNOT: { 976 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); 977 assert( !ExprHasProperty(pExpr, EP_Reduced) ); 978 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE", 979 ** and "x IS NOT FALSE". */ 980 if( pRight->op==TK_ID ){ 981 int rc = resolveExprStep(pWalker, pRight); 982 if( rc==WRC_Abort ) return WRC_Abort; 983 if( pRight->op==TK_TRUEFALSE ){ 984 pExpr->op2 = pExpr->op; 985 pExpr->op = TK_TRUTH; 986 return WRC_Continue; 987 } 988 } 989 /* Fall thru */ 990 } 991 case TK_BETWEEN: 992 case TK_EQ: 993 case TK_NE: 994 case TK_LT: 995 case TK_LE: 996 case TK_GT: 997 case TK_GE: { 998 int nLeft, nRight; 999 if( pParse->db->mallocFailed ) break; 1000 assert( pExpr->pLeft!=0 ); 1001 nLeft = sqlite3ExprVectorSize(pExpr->pLeft); 1002 if( pExpr->op==TK_BETWEEN ){ 1003 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr); 1004 if( nRight==nLeft ){ 1005 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr); 1006 } 1007 }else{ 1008 assert( pExpr->pRight!=0 ); 1009 nRight = sqlite3ExprVectorSize(pExpr->pRight); 1010 } 1011 if( nLeft!=nRight ){ 1012 testcase( pExpr->op==TK_EQ ); 1013 testcase( pExpr->op==TK_NE ); 1014 testcase( pExpr->op==TK_LT ); 1015 testcase( pExpr->op==TK_LE ); 1016 testcase( pExpr->op==TK_GT ); 1017 testcase( pExpr->op==TK_GE ); 1018 testcase( pExpr->op==TK_IS ); 1019 testcase( pExpr->op==TK_ISNOT ); 1020 testcase( pExpr->op==TK_BETWEEN ); 1021 sqlite3ErrorMsg(pParse, "row value misused"); 1022 } 1023 break; 1024 } 1025 } 1026 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; 1027 } 1028 1029 /* 1030 ** pEList is a list of expressions which are really the result set of the 1031 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. 1032 ** This routine checks to see if pE is a simple identifier which corresponds 1033 ** to the AS-name of one of the terms of the expression list. If it is, 1034 ** this routine return an integer between 1 and N where N is the number of 1035 ** elements in pEList, corresponding to the matching entry. If there is 1036 ** no match, or if pE is not a simple identifier, then this routine 1037 ** return 0. 1038 ** 1039 ** pEList has been resolved. pE has not. 1040 */ 1041 static int resolveAsName( 1042 Parse *pParse, /* Parsing context for error messages */ 1043 ExprList *pEList, /* List of expressions to scan */ 1044 Expr *pE /* Expression we are trying to match */ 1045 ){ 1046 int i; /* Loop counter */ 1047 1048 UNUSED_PARAMETER(pParse); 1049 1050 if( pE->op==TK_ID ){ 1051 char *zCol = pE->u.zToken; 1052 for(i=0; i<pEList->nExpr; i++){ 1053 char *zAs = pEList->a[i].zName; 1054 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 1055 return i+1; 1056 } 1057 } 1058 } 1059 return 0; 1060 } 1061 1062 /* 1063 ** pE is a pointer to an expression which is a single term in the 1064 ** ORDER BY of a compound SELECT. The expression has not been 1065 ** name resolved. 1066 ** 1067 ** At the point this routine is called, we already know that the 1068 ** ORDER BY term is not an integer index into the result set. That 1069 ** case is handled by the calling routine. 1070 ** 1071 ** Attempt to match pE against result set columns in the left-most 1072 ** SELECT statement. Return the index i of the matching column, 1073 ** as an indication to the caller that it should sort by the i-th column. 1074 ** The left-most column is 1. In other words, the value returned is the 1075 ** same integer value that would be used in the SQL statement to indicate 1076 ** the column. 1077 ** 1078 ** If there is no match, return 0. Return -1 if an error occurs. 1079 */ 1080 static int resolveOrderByTermToExprList( 1081 Parse *pParse, /* Parsing context for error messages */ 1082 Select *pSelect, /* The SELECT statement with the ORDER BY clause */ 1083 Expr *pE /* The specific ORDER BY term */ 1084 ){ 1085 int i; /* Loop counter */ 1086 ExprList *pEList; /* The columns of the result set */ 1087 NameContext nc; /* Name context for resolving pE */ 1088 sqlite3 *db; /* Database connection */ 1089 int rc; /* Return code from subprocedures */ 1090 u8 savedSuppErr; /* Saved value of db->suppressErr */ 1091 1092 assert( sqlite3ExprIsInteger(pE, &i)==0 ); 1093 pEList = pSelect->pEList; 1094 1095 /* Resolve all names in the ORDER BY term expression 1096 */ 1097 memset(&nc, 0, sizeof(nc)); 1098 nc.pParse = pParse; 1099 nc.pSrcList = pSelect->pSrc; 1100 nc.uNC.pEList = pEList; 1101 nc.ncFlags = NC_AllowAgg|NC_UEList; 1102 nc.nErr = 0; 1103 db = pParse->db; 1104 savedSuppErr = db->suppressErr; 1105 db->suppressErr = 1; 1106 rc = sqlite3ResolveExprNames(&nc, pE); 1107 db->suppressErr = savedSuppErr; 1108 if( rc ) return 0; 1109 1110 /* Try to match the ORDER BY expression against an expression 1111 ** in the result set. Return an 1-based index of the matching 1112 ** result-set entry. 1113 */ 1114 for(i=0; i<pEList->nExpr; i++){ 1115 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){ 1116 return i+1; 1117 } 1118 } 1119 1120 /* If no match, return 0. */ 1121 return 0; 1122 } 1123 1124 /* 1125 ** Generate an ORDER BY or GROUP BY term out-of-range error. 1126 */ 1127 static void resolveOutOfRangeError( 1128 Parse *pParse, /* The error context into which to write the error */ 1129 const char *zType, /* "ORDER" or "GROUP" */ 1130 int i, /* The index (1-based) of the term out of range */ 1131 int mx /* Largest permissible value of i */ 1132 ){ 1133 sqlite3ErrorMsg(pParse, 1134 "%r %s BY term out of range - should be " 1135 "between 1 and %d", i, zType, mx); 1136 } 1137 1138 /* 1139 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify 1140 ** each term of the ORDER BY clause is a constant integer between 1 1141 ** and N where N is the number of columns in the compound SELECT. 1142 ** 1143 ** ORDER BY terms that are already an integer between 1 and N are 1144 ** unmodified. ORDER BY terms that are integers outside the range of 1145 ** 1 through N generate an error. ORDER BY terms that are expressions 1146 ** are matched against result set expressions of compound SELECT 1147 ** beginning with the left-most SELECT and working toward the right. 1148 ** At the first match, the ORDER BY expression is transformed into 1149 ** the integer column number. 1150 ** 1151 ** Return the number of errors seen. 1152 */ 1153 static int resolveCompoundOrderBy( 1154 Parse *pParse, /* Parsing context. Leave error messages here */ 1155 Select *pSelect /* The SELECT statement containing the ORDER BY */ 1156 ){ 1157 int i; 1158 ExprList *pOrderBy; 1159 ExprList *pEList; 1160 sqlite3 *db; 1161 int moreToDo = 1; 1162 1163 pOrderBy = pSelect->pOrderBy; 1164 if( pOrderBy==0 ) return 0; 1165 db = pParse->db; 1166 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1167 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); 1168 return 1; 1169 } 1170 for(i=0; i<pOrderBy->nExpr; i++){ 1171 pOrderBy->a[i].done = 0; 1172 } 1173 pSelect->pNext = 0; 1174 while( pSelect->pPrior ){ 1175 pSelect->pPrior->pNext = pSelect; 1176 pSelect = pSelect->pPrior; 1177 } 1178 while( pSelect && moreToDo ){ 1179 struct ExprList_item *pItem; 1180 moreToDo = 0; 1181 pEList = pSelect->pEList; 1182 assert( pEList!=0 ); 1183 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 1184 int iCol = -1; 1185 Expr *pE, *pDup; 1186 if( pItem->done ) continue; 1187 pE = sqlite3ExprSkipCollate(pItem->pExpr); 1188 if( sqlite3ExprIsInteger(pE, &iCol) ){ 1189 if( iCol<=0 || iCol>pEList->nExpr ){ 1190 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); 1191 return 1; 1192 } 1193 }else{ 1194 iCol = resolveAsName(pParse, pEList, pE); 1195 if( iCol==0 ){ 1196 /* Now test if expression pE matches one of the values returned 1197 ** by pSelect. In the usual case this is done by duplicating the 1198 ** expression, resolving any symbols in it, and then comparing 1199 ** it against each expression returned by the SELECT statement. 1200 ** Once the comparisons are finished, the duplicate expression 1201 ** is deleted. 1202 ** 1203 ** Or, if this is running as part of an ALTER TABLE operation, 1204 ** resolve the symbols in the actual expression, not a duplicate. 1205 ** And, if one of the comparisons is successful, leave the expression 1206 ** as is instead of transforming it to an integer as in the usual 1207 ** case. This allows the code in alter.c to modify column 1208 ** refererences within the ORDER BY expression as required. */ 1209 if( IN_RENAME_OBJECT ){ 1210 pDup = pE; 1211 }else{ 1212 pDup = sqlite3ExprDup(db, pE, 0); 1213 } 1214 if( !db->mallocFailed ){ 1215 assert(pDup); 1216 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); 1217 } 1218 if( !IN_RENAME_OBJECT ){ 1219 sqlite3ExprDelete(db, pDup); 1220 } 1221 } 1222 } 1223 if( iCol>0 ){ 1224 /* Convert the ORDER BY term into an integer column number iCol, 1225 ** taking care to preserve the COLLATE clause if it exists */ 1226 if( !IN_RENAME_OBJECT ){ 1227 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 1228 if( pNew==0 ) return 1; 1229 pNew->flags |= EP_IntValue; 1230 pNew->u.iValue = iCol; 1231 if( pItem->pExpr==pE ){ 1232 pItem->pExpr = pNew; 1233 }else{ 1234 Expr *pParent = pItem->pExpr; 1235 assert( pParent->op==TK_COLLATE ); 1236 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft; 1237 assert( pParent->pLeft==pE ); 1238 pParent->pLeft = pNew; 1239 } 1240 sqlite3ExprDelete(db, pE); 1241 pItem->u.x.iOrderByCol = (u16)iCol; 1242 } 1243 pItem->done = 1; 1244 }else{ 1245 moreToDo = 1; 1246 } 1247 } 1248 pSelect = pSelect->pNext; 1249 } 1250 for(i=0; i<pOrderBy->nExpr; i++){ 1251 if( pOrderBy->a[i].done==0 ){ 1252 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " 1253 "column in the result set", i+1); 1254 return 1; 1255 } 1256 } 1257 return 0; 1258 } 1259 1260 /* 1261 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of 1262 ** the SELECT statement pSelect. If any term is reference to a 1263 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol 1264 ** field) then convert that term into a copy of the corresponding result set 1265 ** column. 1266 ** 1267 ** If any errors are detected, add an error message to pParse and 1268 ** return non-zero. Return zero if no errors are seen. 1269 */ 1270 int sqlite3ResolveOrderGroupBy( 1271 Parse *pParse, /* Parsing context. Leave error messages here */ 1272 Select *pSelect, /* The SELECT statement containing the clause */ 1273 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 1274 const char *zType /* "ORDER" or "GROUP" */ 1275 ){ 1276 int i; 1277 sqlite3 *db = pParse->db; 1278 ExprList *pEList; 1279 struct ExprList_item *pItem; 1280 1281 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0; 1282 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1283 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 1284 return 1; 1285 } 1286 pEList = pSelect->pEList; 1287 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ 1288 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 1289 if( pItem->u.x.iOrderByCol ){ 1290 if( pItem->u.x.iOrderByCol>pEList->nExpr ){ 1291 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr); 1292 return 1; 1293 } 1294 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, 1295 zType,0); 1296 } 1297 } 1298 return 0; 1299 } 1300 1301 #ifndef SQLITE_OMIT_WINDOWFUNC 1302 /* 1303 ** Walker callback for windowRemoveExprFromSelect(). 1304 */ 1305 static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){ 1306 UNUSED_PARAMETER(pWalker); 1307 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 1308 Window *pWin = pExpr->y.pWin; 1309 sqlite3WindowUnlinkFromSelect(pWin); 1310 } 1311 return WRC_Continue; 1312 } 1313 1314 /* 1315 ** Remove any Window objects owned by the expression pExpr from the 1316 ** Select.pWin list of Select object pSelect. 1317 */ 1318 static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){ 1319 if( pSelect->pWin ){ 1320 Walker sWalker; 1321 memset(&sWalker, 0, sizeof(Walker)); 1322 sWalker.xExprCallback = resolveRemoveWindowsCb; 1323 sWalker.u.pSelect = pSelect; 1324 sqlite3WalkExpr(&sWalker, pExpr); 1325 } 1326 } 1327 #else 1328 # define windowRemoveExprFromSelect(a, b) 1329 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1330 1331 /* 1332 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. 1333 ** The Name context of the SELECT statement is pNC. zType is either 1334 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. 1335 ** 1336 ** This routine resolves each term of the clause into an expression. 1337 ** If the order-by term is an integer I between 1 and N (where N is the 1338 ** number of columns in the result set of the SELECT) then the expression 1339 ** in the resolution is a copy of the I-th result-set expression. If 1340 ** the order-by term is an identifier that corresponds to the AS-name of 1341 ** a result-set expression, then the term resolves to a copy of the 1342 ** result-set expression. Otherwise, the expression is resolved in 1343 ** the usual way - using sqlite3ResolveExprNames(). 1344 ** 1345 ** This routine returns the number of errors. If errors occur, then 1346 ** an appropriate error message might be left in pParse. (OOM errors 1347 ** excepted.) 1348 */ 1349 static int resolveOrderGroupBy( 1350 NameContext *pNC, /* The name context of the SELECT statement */ 1351 Select *pSelect, /* The SELECT statement holding pOrderBy */ 1352 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ 1353 const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 1354 ){ 1355 int i, j; /* Loop counters */ 1356 int iCol; /* Column number */ 1357 struct ExprList_item *pItem; /* A term of the ORDER BY clause */ 1358 Parse *pParse; /* Parsing context */ 1359 int nResult; /* Number of terms in the result set */ 1360 1361 if( pOrderBy==0 ) return 0; 1362 nResult = pSelect->pEList->nExpr; 1363 pParse = pNC->pParse; 1364 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 1365 Expr *pE = pItem->pExpr; 1366 Expr *pE2 = sqlite3ExprSkipCollate(pE); 1367 if( zType[0]!='G' ){ 1368 iCol = resolveAsName(pParse, pSelect->pEList, pE2); 1369 if( iCol>0 ){ 1370 /* If an AS-name match is found, mark this ORDER BY column as being 1371 ** a copy of the iCol-th result-set column. The subsequent call to 1372 ** sqlite3ResolveOrderGroupBy() will convert the expression to a 1373 ** copy of the iCol-th result-set expression. */ 1374 pItem->u.x.iOrderByCol = (u16)iCol; 1375 continue; 1376 } 1377 } 1378 if( sqlite3ExprIsInteger(pE2, &iCol) ){ 1379 /* The ORDER BY term is an integer constant. Again, set the column 1380 ** number so that sqlite3ResolveOrderGroupBy() will convert the 1381 ** order-by term to a copy of the result-set expression */ 1382 if( iCol<1 || iCol>0xffff ){ 1383 resolveOutOfRangeError(pParse, zType, i+1, nResult); 1384 return 1; 1385 } 1386 pItem->u.x.iOrderByCol = (u16)iCol; 1387 continue; 1388 } 1389 1390 /* Otherwise, treat the ORDER BY term as an ordinary expression */ 1391 pItem->u.x.iOrderByCol = 0; 1392 if( sqlite3ResolveExprNames(pNC, pE) ){ 1393 return 1; 1394 } 1395 for(j=0; j<pSelect->pEList->nExpr; j++){ 1396 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ 1397 /* Since this expresion is being changed into a reference 1398 ** to an identical expression in the result set, remove all Window 1399 ** objects belonging to the expression from the Select.pWin list. */ 1400 windowRemoveExprFromSelect(pSelect, pE); 1401 pItem->u.x.iOrderByCol = j+1; 1402 } 1403 } 1404 } 1405 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); 1406 } 1407 1408 /* 1409 ** Resolve names in the SELECT statement p and all of its descendants. 1410 */ 1411 static int resolveSelectStep(Walker *pWalker, Select *p){ 1412 NameContext *pOuterNC; /* Context that contains this SELECT */ 1413 NameContext sNC; /* Name context of this SELECT */ 1414 int isCompound; /* True if p is a compound select */ 1415 int nCompound; /* Number of compound terms processed so far */ 1416 Parse *pParse; /* Parsing context */ 1417 int i; /* Loop counter */ 1418 ExprList *pGroupBy; /* The GROUP BY clause */ 1419 Select *pLeftmost; /* Left-most of SELECT of a compound */ 1420 sqlite3 *db; /* Database connection */ 1421 1422 1423 assert( p!=0 ); 1424 if( p->selFlags & SF_Resolved ){ 1425 return WRC_Prune; 1426 } 1427 pOuterNC = pWalker->u.pNC; 1428 pParse = pWalker->pParse; 1429 db = pParse->db; 1430 1431 /* Normally sqlite3SelectExpand() will be called first and will have 1432 ** already expanded this SELECT. However, if this is a subquery within 1433 ** an expression, sqlite3ResolveExprNames() will be called without a 1434 ** prior call to sqlite3SelectExpand(). When that happens, let 1435 ** sqlite3SelectPrep() do all of the processing for this SELECT. 1436 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and 1437 ** this routine in the correct order. 1438 */ 1439 if( (p->selFlags & SF_Expanded)==0 ){ 1440 sqlite3SelectPrep(pParse, p, pOuterNC); 1441 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; 1442 } 1443 1444 isCompound = p->pPrior!=0; 1445 nCompound = 0; 1446 pLeftmost = p; 1447 while( p ){ 1448 assert( (p->selFlags & SF_Expanded)!=0 ); 1449 assert( (p->selFlags & SF_Resolved)==0 ); 1450 p->selFlags |= SF_Resolved; 1451 1452 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 1453 ** are not allowed to refer to any names, so pass an empty NameContext. 1454 */ 1455 memset(&sNC, 0, sizeof(sNC)); 1456 sNC.pParse = pParse; 1457 sNC.pWinSelect = p; 1458 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){ 1459 return WRC_Abort; 1460 } 1461 1462 /* If the SF_Converted flags is set, then this Select object was 1463 ** was created by the convertCompoundSelectToSubquery() function. 1464 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved 1465 ** as if it were part of the sub-query, not the parent. This block 1466 ** moves the pOrderBy down to the sub-query. It will be moved back 1467 ** after the names have been resolved. */ 1468 if( p->selFlags & SF_Converted ){ 1469 Select *pSub = p->pSrc->a[0].pSelect; 1470 assert( p->pSrc->nSrc==1 && p->pOrderBy ); 1471 assert( pSub->pPrior && pSub->pOrderBy==0 ); 1472 pSub->pOrderBy = p->pOrderBy; 1473 p->pOrderBy = 0; 1474 } 1475 1476 /* Recursively resolve names in all subqueries 1477 */ 1478 for(i=0; i<p->pSrc->nSrc; i++){ 1479 struct SrcList_item *pItem = &p->pSrc->a[i]; 1480 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){ 1481 NameContext *pNC; /* Used to iterate name contexts */ 1482 int nRef = 0; /* Refcount for pOuterNC and outer contexts */ 1483 const char *zSavedContext = pParse->zAuthContext; 1484 1485 /* Count the total number of references to pOuterNC and all of its 1486 ** parent contexts. After resolving references to expressions in 1487 ** pItem->pSelect, check if this value has changed. If so, then 1488 ** SELECT statement pItem->pSelect must be correlated. Set the 1489 ** pItem->fg.isCorrelated flag if this is the case. */ 1490 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef; 1491 1492 if( pItem->zName ) pParse->zAuthContext = pItem->zName; 1493 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); 1494 pParse->zAuthContext = zSavedContext; 1495 if( pParse->nErr || db->mallocFailed ) return WRC_Abort; 1496 1497 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef; 1498 assert( pItem->fg.isCorrelated==0 && nRef<=0 ); 1499 pItem->fg.isCorrelated = (nRef!=0); 1500 } 1501 } 1502 1503 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to 1504 ** resolve the result-set expression list. 1505 */ 1506 sNC.ncFlags = NC_AllowAgg|NC_AllowWin; 1507 sNC.pSrcList = p->pSrc; 1508 sNC.pNext = pOuterNC; 1509 1510 /* Resolve names in the result set. */ 1511 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; 1512 sNC.ncFlags &= ~NC_AllowWin; 1513 1514 /* If there are no aggregate functions in the result-set, and no GROUP BY 1515 ** expression, do not allow aggregates in any of the other expressions. 1516 */ 1517 assert( (p->selFlags & SF_Aggregate)==0 ); 1518 pGroupBy = p->pGroupBy; 1519 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){ 1520 assert( NC_MinMaxAgg==SF_MinMaxAgg ); 1521 p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg); 1522 }else{ 1523 sNC.ncFlags &= ~NC_AllowAgg; 1524 } 1525 1526 /* If a HAVING clause is present, then there must be a GROUP BY clause. 1527 */ 1528 if( p->pHaving && !pGroupBy ){ 1529 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 1530 return WRC_Abort; 1531 } 1532 1533 /* Add the output column list to the name-context before parsing the 1534 ** other expressions in the SELECT statement. This is so that 1535 ** expressions in the WHERE clause (etc.) can refer to expressions by 1536 ** aliases in the result set. 1537 ** 1538 ** Minor point: If this is the case, then the expression will be 1539 ** re-evaluated for each reference to it. 1540 */ 1541 assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 ); 1542 sNC.uNC.pEList = p->pEList; 1543 sNC.ncFlags |= NC_UEList; 1544 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; 1545 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; 1546 1547 /* Resolve names in table-valued-function arguments */ 1548 for(i=0; i<p->pSrc->nSrc; i++){ 1549 struct SrcList_item *pItem = &p->pSrc->a[i]; 1550 if( pItem->fg.isTabFunc 1551 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) 1552 ){ 1553 return WRC_Abort; 1554 } 1555 } 1556 1557 /* The ORDER BY and GROUP BY clauses may not refer to terms in 1558 ** outer queries 1559 */ 1560 sNC.pNext = 0; 1561 sNC.ncFlags |= NC_AllowAgg|NC_AllowWin; 1562 1563 /* If this is a converted compound query, move the ORDER BY clause from 1564 ** the sub-query back to the parent query. At this point each term 1565 ** within the ORDER BY clause has been transformed to an integer value. 1566 ** These integers will be replaced by copies of the corresponding result 1567 ** set expressions by the call to resolveOrderGroupBy() below. */ 1568 if( p->selFlags & SF_Converted ){ 1569 Select *pSub = p->pSrc->a[0].pSelect; 1570 p->pOrderBy = pSub->pOrderBy; 1571 pSub->pOrderBy = 0; 1572 } 1573 1574 /* Process the ORDER BY clause for singleton SELECT statements. 1575 ** The ORDER BY clause for compounds SELECT statements is handled 1576 ** below, after all of the result-sets for all of the elements of 1577 ** the compound have been resolved. 1578 ** 1579 ** If there is an ORDER BY clause on a term of a compound-select other 1580 ** than the right-most term, then that is a syntax error. But the error 1581 ** is not detected until much later, and so we need to go ahead and 1582 ** resolve those symbols on the incorrect ORDER BY for consistency. 1583 */ 1584 if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */ 1585 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") 1586 ){ 1587 return WRC_Abort; 1588 } 1589 if( db->mallocFailed ){ 1590 return WRC_Abort; 1591 } 1592 sNC.ncFlags &= ~NC_AllowWin; 1593 1594 /* Resolve the GROUP BY clause. At the same time, make sure 1595 ** the GROUP BY clause does not contain aggregate functions. 1596 */ 1597 if( pGroupBy ){ 1598 struct ExprList_item *pItem; 1599 1600 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ 1601 return WRC_Abort; 1602 } 1603 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 1604 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 1605 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 1606 "the GROUP BY clause"); 1607 return WRC_Abort; 1608 } 1609 } 1610 } 1611 1612 #ifndef SQLITE_OMIT_WINDOWFUNC 1613 if( IN_RENAME_OBJECT ){ 1614 Window *pWin; 1615 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){ 1616 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy) 1617 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition) 1618 ){ 1619 return WRC_Abort; 1620 } 1621 } 1622 } 1623 #endif 1624 1625 /* If this is part of a compound SELECT, check that it has the right 1626 ** number of expressions in the select list. */ 1627 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){ 1628 sqlite3SelectWrongNumTermsError(pParse, p->pNext); 1629 return WRC_Abort; 1630 } 1631 1632 /* Advance to the next term of the compound 1633 */ 1634 p = p->pPrior; 1635 nCompound++; 1636 } 1637 1638 /* Resolve the ORDER BY on a compound SELECT after all terms of 1639 ** the compound have been resolved. 1640 */ 1641 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ 1642 return WRC_Abort; 1643 } 1644 1645 return WRC_Prune; 1646 } 1647 1648 /* 1649 ** This routine walks an expression tree and resolves references to 1650 ** table columns and result-set columns. At the same time, do error 1651 ** checking on function usage and set a flag if any aggregate functions 1652 ** are seen. 1653 ** 1654 ** To resolve table columns references we look for nodes (or subtrees) of the 1655 ** form X.Y.Z or Y.Z or just Z where 1656 ** 1657 ** X: The name of a database. Ex: "main" or "temp" or 1658 ** the symbolic name assigned to an ATTACH-ed database. 1659 ** 1660 ** Y: The name of a table in a FROM clause. Or in a trigger 1661 ** one of the special names "old" or "new". 1662 ** 1663 ** Z: The name of a column in table Y. 1664 ** 1665 ** The node at the root of the subtree is modified as follows: 1666 ** 1667 ** Expr.op Changed to TK_COLUMN 1668 ** Expr.pTab Points to the Table object for X.Y 1669 ** Expr.iColumn The column index in X.Y. -1 for the rowid. 1670 ** Expr.iTable The VDBE cursor number for X.Y 1671 ** 1672 ** 1673 ** To resolve result-set references, look for expression nodes of the 1674 ** form Z (with no X and Y prefix) where the Z matches the right-hand 1675 ** size of an AS clause in the result-set of a SELECT. The Z expression 1676 ** is replaced by a copy of the left-hand side of the result-set expression. 1677 ** Table-name and function resolution occurs on the substituted expression 1678 ** tree. For example, in: 1679 ** 1680 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; 1681 ** 1682 ** The "x" term of the order by is replaced by "a+b" to render: 1683 ** 1684 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; 1685 ** 1686 ** Function calls are checked to make sure that the function is 1687 ** defined and that the correct number of arguments are specified. 1688 ** If the function is an aggregate function, then the NC_HasAgg flag is 1689 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. 1690 ** If an expression contains aggregate functions then the EP_Agg 1691 ** property on the expression is set. 1692 ** 1693 ** An error message is left in pParse if anything is amiss. The number 1694 ** if errors is returned. 1695 */ 1696 int sqlite3ResolveExprNames( 1697 NameContext *pNC, /* Namespace to resolve expressions in. */ 1698 Expr *pExpr /* The expression to be analyzed. */ 1699 ){ 1700 int savedHasAgg; 1701 Walker w; 1702 1703 if( pExpr==0 ) return SQLITE_OK; 1704 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin); 1705 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin); 1706 w.pParse = pNC->pParse; 1707 w.xExprCallback = resolveExprStep; 1708 w.xSelectCallback = resolveSelectStep; 1709 w.xSelectCallback2 = 0; 1710 w.u.pNC = pNC; 1711 #if SQLITE_MAX_EXPR_DEPTH>0 1712 w.pParse->nHeight += pExpr->nHeight; 1713 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){ 1714 return SQLITE_ERROR; 1715 } 1716 #endif 1717 sqlite3WalkExpr(&w, pExpr); 1718 #if SQLITE_MAX_EXPR_DEPTH>0 1719 w.pParse->nHeight -= pExpr->nHeight; 1720 #endif 1721 assert( EP_Agg==NC_HasAgg ); 1722 assert( EP_Win==NC_HasWin ); 1723 testcase( pNC->ncFlags & NC_HasAgg ); 1724 testcase( pNC->ncFlags & NC_HasWin ); 1725 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) ); 1726 pNC->ncFlags |= savedHasAgg; 1727 return pNC->nErr>0 || w.pParse->nErr>0; 1728 } 1729 1730 /* 1731 ** Resolve all names for all expression in an expression list. This is 1732 ** just like sqlite3ResolveExprNames() except that it works for an expression 1733 ** list rather than a single expression. 1734 */ 1735 int sqlite3ResolveExprListNames( 1736 NameContext *pNC, /* Namespace to resolve expressions in. */ 1737 ExprList *pList /* The expression list to be analyzed. */ 1738 ){ 1739 int i; 1740 if( pList ){ 1741 for(i=0; i<pList->nExpr; i++){ 1742 if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort; 1743 } 1744 } 1745 return WRC_Continue; 1746 } 1747 1748 /* 1749 ** Resolve all names in all expressions of a SELECT and in all 1750 ** decendents of the SELECT, including compounds off of p->pPrior, 1751 ** subqueries in expressions, and subqueries used as FROM clause 1752 ** terms. 1753 ** 1754 ** See sqlite3ResolveExprNames() for a description of the kinds of 1755 ** transformations that occur. 1756 ** 1757 ** All SELECT statements should have been expanded using 1758 ** sqlite3SelectExpand() prior to invoking this routine. 1759 */ 1760 void sqlite3ResolveSelectNames( 1761 Parse *pParse, /* The parser context */ 1762 Select *p, /* The SELECT statement being coded. */ 1763 NameContext *pOuterNC /* Name context for parent SELECT statement */ 1764 ){ 1765 Walker w; 1766 1767 assert( p!=0 ); 1768 w.xExprCallback = resolveExprStep; 1769 w.xSelectCallback = resolveSelectStep; 1770 w.xSelectCallback2 = 0; 1771 w.pParse = pParse; 1772 w.u.pNC = pOuterNC; 1773 sqlite3WalkSelect(&w, p); 1774 } 1775 1776 /* 1777 ** Resolve names in expressions that can only reference a single table 1778 ** or which cannot reference any tables at all. Examples: 1779 ** 1780 ** (1) CHECK constraints 1781 ** (2) WHERE clauses on partial indices 1782 ** (3) Expressions in indexes on expressions 1783 ** (4) Expression arguments to VACUUM INTO. 1784 ** 1785 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN 1786 ** nodes of the expression is set to -1 and the Expr.iColumn value is 1787 ** set to the column number. In case (4), TK_COLUMN nodes cause an error. 1788 ** 1789 ** Any errors cause an error message to be set in pParse. 1790 */ 1791 int sqlite3ResolveSelfReference( 1792 Parse *pParse, /* Parsing context */ 1793 Table *pTab, /* The table being referenced, or NULL */ 1794 int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr, or 0 */ 1795 Expr *pExpr, /* Expression to resolve. May be NULL. */ 1796 ExprList *pList /* Expression list to resolve. May be NULL. */ 1797 ){ 1798 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ 1799 NameContext sNC; /* Name context for pParse->pNewTable */ 1800 int rc; 1801 1802 assert( type==0 || pTab!=0 ); 1803 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr || pTab==0 ); 1804 memset(&sNC, 0, sizeof(sNC)); 1805 memset(&sSrc, 0, sizeof(sSrc)); 1806 if( pTab ){ 1807 sSrc.nSrc = 1; 1808 sSrc.a[0].zName = pTab->zName; 1809 sSrc.a[0].pTab = pTab; 1810 sSrc.a[0].iCursor = -1; 1811 } 1812 sNC.pParse = pParse; 1813 sNC.pSrcList = &sSrc; 1814 sNC.ncFlags = type | NC_IsDDL; 1815 if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc; 1816 if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList); 1817 return rc; 1818 } 1819