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