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