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