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