000001 /* 000002 ** 2008 August 18 000003 ** 000004 ** The author disclaims copyright to this source code. In place of 000005 ** a legal notice, here is a blessing: 000006 ** 000007 ** May you do good and not evil. 000008 ** May you find forgiveness for yourself and forgive others. 000009 ** May you share freely, never taking more than you give. 000010 ** 000011 ************************************************************************* 000012 ** 000013 ** This file contains routines used for walking the parser tree and 000014 ** resolve all identifiers by associating them with a particular 000015 ** table and column. 000016 */ 000017 #include "sqliteInt.h" 000018 000019 /* 000020 ** Walk the expression tree pExpr and increase the aggregate function 000021 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node. 000022 ** This needs to occur when copying a TK_AGG_FUNCTION node from an 000023 ** outer query into an inner subquery. 000024 ** 000025 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..) 000026 ** is a helper function - a callback for the tree walker. 000027 */ 000028 static int incrAggDepth(Walker *pWalker, Expr *pExpr){ 000029 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n; 000030 return WRC_Continue; 000031 } 000032 static void incrAggFunctionDepth(Expr *pExpr, int N){ 000033 if( N>0 ){ 000034 Walker w; 000035 memset(&w, 0, sizeof(w)); 000036 w.xExprCallback = incrAggDepth; 000037 w.u.n = N; 000038 sqlite3WalkExpr(&w, pExpr); 000039 } 000040 } 000041 000042 /* 000043 ** Turn the pExpr expression into an alias for the iCol-th column of the 000044 ** result set in pEList. 000045 ** 000046 ** If the reference is followed by a COLLATE operator, then make sure 000047 ** the COLLATE operator is preserved. For example: 000048 ** 000049 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase; 000050 ** 000051 ** Should be transformed into: 000052 ** 000053 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase; 000054 ** 000055 ** The nSubquery parameter specifies how many levels of subquery the 000056 ** alias is removed from the original expression. The usual value is 000057 ** zero but it might be more if the alias is contained within a subquery 000058 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION 000059 ** structures must be increased by the nSubquery amount. 000060 */ 000061 static void resolveAlias( 000062 Parse *pParse, /* Parsing context */ 000063 ExprList *pEList, /* A result set */ 000064 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ 000065 Expr *pExpr, /* Transform this into an alias to the result set */ 000066 const char *zType, /* "GROUP" or "ORDER" or "" */ 000067 int nSubquery /* Number of subqueries that the label is moving */ 000068 ){ 000069 Expr *pOrig; /* The iCol-th column of the result set */ 000070 Expr *pDup; /* Copy of pOrig */ 000071 sqlite3 *db; /* The database connection */ 000072 000073 assert( iCol>=0 && iCol<pEList->nExpr ); 000074 pOrig = pEList->a[iCol].pExpr; 000075 assert( pOrig!=0 ); 000076 db = pParse->db; 000077 pDup = sqlite3ExprDup(db, pOrig, 0); 000078 if( pDup!=0 ){ 000079 if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery); 000080 if( pExpr->op==TK_COLLATE ){ 000081 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); 000082 } 000083 000084 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 000085 ** prevents ExprDelete() from deleting the Expr structure itself, 000086 ** allowing it to be repopulated by the memcpy() on the following line. 000087 ** The pExpr->u.zToken might point into memory that will be freed by the 000088 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to 000089 ** make a copy of the token before doing the sqlite3DbFree(). 000090 */ 000091 ExprSetProperty(pExpr, EP_Static); 000092 sqlite3ExprDelete(db, pExpr); 000093 memcpy(pExpr, pDup, sizeof(*pExpr)); 000094 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){ 000095 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 ); 000096 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken); 000097 pExpr->flags |= EP_MemToken; 000098 } 000099 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 000100 if( pExpr->y.pWin!=0 ){ 000101 pExpr->y.pWin->pOwner = pExpr; 000102 }else{ 000103 assert( db->mallocFailed ); 000104 } 000105 } 000106 sqlite3DbFree(db, pDup); 000107 } 000108 ExprSetProperty(pExpr, EP_Alias); 000109 } 000110 000111 000112 /* 000113 ** Return TRUE if the name zCol occurs anywhere in the USING clause. 000114 ** 000115 ** Return FALSE if the USING clause is NULL or if it does not contain 000116 ** zCol. 000117 */ 000118 static int nameInUsingClause(IdList *pUsing, const char *zCol){ 000119 if( pUsing ){ 000120 int k; 000121 for(k=0; k<pUsing->nId; k++){ 000122 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1; 000123 } 000124 } 000125 return 0; 000126 } 000127 000128 /* 000129 ** Subqueries stores the original database, table and column names for their 000130 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN". 000131 ** Check to see if the zSpan given to this routine matches the zDb, zTab, 000132 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will 000133 ** match anything. 000134 */ 000135 int sqlite3MatchSpanName( 000136 const char *zSpan, 000137 const char *zCol, 000138 const char *zTab, 000139 const char *zDb 000140 ){ 000141 int n; 000142 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} 000143 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ 000144 return 0; 000145 } 000146 zSpan += n+1; 000147 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} 000148 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ 000149 return 0; 000150 } 000151 zSpan += n+1; 000152 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){ 000153 return 0; 000154 } 000155 return 1; 000156 } 000157 000158 /* 000159 ** Return TRUE if the double-quoted string mis-feature should be supported. 000160 */ 000161 static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){ 000162 if( db->init.busy ) return 1; /* Always support for legacy schemas */ 000163 if( pTopNC->ncFlags & NC_IsDDL ){ 000164 /* Currently parsing a DDL statement */ 000165 if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){ 000166 return 1; 000167 } 000168 return (db->flags & SQLITE_DqsDDL)!=0; 000169 }else{ 000170 /* Currently parsing a DML statement */ 000171 return (db->flags & SQLITE_DqsDML)!=0; 000172 } 000173 } 000174 000175 /* 000176 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up 000177 ** that name in the set of source tables in pSrcList and make the pExpr 000178 ** expression node refer back to that source column. The following changes 000179 ** are made to pExpr: 000180 ** 000181 ** pExpr->iDb Set the index in db->aDb[] of the database X 000182 ** (even if X is implied). 000183 ** pExpr->iTable Set to the cursor number for the table obtained 000184 ** from pSrcList. 000185 ** pExpr->y.pTab Points to the Table structure of X.Y (even if 000186 ** X and/or Y are implied.) 000187 ** pExpr->iColumn Set to the column number within the table. 000188 ** pExpr->op Set to TK_COLUMN. 000189 ** pExpr->pLeft Any expression this points to is deleted 000190 ** pExpr->pRight Any expression this points to is deleted. 000191 ** 000192 ** The zDb variable is the name of the database (the "X"). This value may be 000193 ** NULL meaning that name is of the form Y.Z or Z. Any available database 000194 ** can be used. The zTable variable is the name of the table (the "Y"). This 000195 ** value can be NULL if zDb is also NULL. If zTable is NULL it 000196 ** means that the form of the name is Z and that columns from any table 000197 ** can be used. 000198 ** 000199 ** If the name cannot be resolved unambiguously, leave an error message 000200 ** in pParse and return WRC_Abort. Return WRC_Prune on success. 000201 */ 000202 static int lookupName( 000203 Parse *pParse, /* The parsing context */ 000204 const char *zDb, /* Name of the database containing table, or NULL */ 000205 const char *zTab, /* Name of table containing column, or NULL */ 000206 const char *zCol, /* Name of the column. */ 000207 NameContext *pNC, /* The name context used to resolve the name */ 000208 Expr *pExpr /* Make this EXPR node point to the selected column */ 000209 ){ 000210 int i, j; /* Loop counters */ 000211 int cnt = 0; /* Number of matching column names */ 000212 int cntTab = 0; /* Number of matching table names */ 000213 int nSubquery = 0; /* How many levels of subquery */ 000214 sqlite3 *db = pParse->db; /* The database connection */ 000215 struct SrcList_item *pItem; /* Use for looping over pSrcList items */ 000216 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ 000217 NameContext *pTopNC = pNC; /* First namecontext in the list */ 000218 Schema *pSchema = 0; /* Schema of the expression */ 000219 int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ 000220 Table *pTab = 0; /* Table hold the row */ 000221 Column *pCol; /* A column of pTab */ 000222 000223 assert( pNC ); /* the name context cannot be NULL. */ 000224 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ 000225 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 000226 000227 /* Initialize the node to no-match */ 000228 pExpr->iTable = -1; 000229 ExprSetVVAProperty(pExpr, EP_NoReduce); 000230 000231 /* Translate the schema name in zDb into a pointer to the corresponding 000232 ** schema. If not found, pSchema will remain NULL and nothing will match 000233 ** resulting in an appropriate error message toward the end of this routine 000234 */ 000235 if( zDb ){ 000236 testcase( pNC->ncFlags & NC_PartIdx ); 000237 testcase( pNC->ncFlags & NC_IsCheck ); 000238 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ 000239 /* Silently ignore database qualifiers inside CHECK constraints and 000240 ** partial indices. Do not raise errors because that might break 000241 ** legacy and because it does not hurt anything to just ignore the 000242 ** database name. */ 000243 zDb = 0; 000244 }else{ 000245 for(i=0; i<db->nDb; i++){ 000246 assert( db->aDb[i].zDbSName ); 000247 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ 000248 pSchema = db->aDb[i].pSchema; 000249 break; 000250 } 000251 } 000252 } 000253 } 000254 000255 /* Start at the inner-most context and move outward until a match is found */ 000256 assert( pNC && cnt==0 ); 000257 do{ 000258 ExprList *pEList; 000259 SrcList *pSrcList = pNC->pSrcList; 000260 000261 if( pSrcList ){ 000262 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ 000263 pTab = pItem->pTab; 000264 assert( pTab!=0 && pTab->zName!=0 ); 000265 assert( pTab->nCol>0 ); 000266 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ 000267 int hit = 0; 000268 pEList = pItem->pSelect->pEList; 000269 for(j=0; j<pEList->nExpr; j++){ 000270 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ 000271 cnt++; 000272 cntTab = 2; 000273 pMatch = pItem; 000274 pExpr->iColumn = j; 000275 hit = 1; 000276 } 000277 } 000278 if( hit || zTab==0 ) continue; 000279 } 000280 if( zDb && pTab->pSchema!=pSchema ){ 000281 continue; 000282 } 000283 if( zTab ){ 000284 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; 000285 assert( zTabName!=0 ); 000286 if( sqlite3StrICmp(zTabName, zTab)!=0 ){ 000287 continue; 000288 } 000289 if( IN_RENAME_OBJECT && pItem->zAlias ){ 000290 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); 000291 } 000292 } 000293 if( 0==(cntTab++) ){ 000294 pMatch = pItem; 000295 } 000296 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ 000297 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ 000298 /* If there has been exactly one prior match and this match 000299 ** is for the right-hand table of a NATURAL JOIN or is in a 000300 ** USING clause, then skip this match. 000301 */ 000302 if( cnt==1 ){ 000303 if( pItem->fg.jointype & JT_NATURAL ) continue; 000304 if( nameInUsingClause(pItem->pUsing, zCol) ) continue; 000305 } 000306 cnt++; 000307 pMatch = pItem; 000308 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ 000309 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; 000310 break; 000311 } 000312 } 000313 } 000314 if( pMatch ){ 000315 pExpr->iTable = pMatch->iCursor; 000316 pExpr->y.pTab = pMatch->pTab; 000317 /* RIGHT JOIN not (yet) supported */ 000318 assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); 000319 if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ 000320 ExprSetProperty(pExpr, EP_CanBeNull); 000321 } 000322 pSchema = pExpr->y.pTab->pSchema; 000323 } 000324 } /* if( pSrcList ) */ 000325 000326 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) 000327 /* If we have not already resolved the name, then maybe 000328 ** it is a new.* or old.* trigger argument reference. Or 000329 ** maybe it is an excluded.* from an upsert. 000330 */ 000331 if( zDb==0 && zTab!=0 && cntTab==0 ){ 000332 pTab = 0; 000333 #ifndef SQLITE_OMIT_TRIGGER 000334 if( pParse->pTriggerTab!=0 ){ 000335 int op = pParse->eTriggerOp; 000336 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); 000337 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ 000338 pExpr->iTable = 1; 000339 pTab = pParse->pTriggerTab; 000340 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ 000341 pExpr->iTable = 0; 000342 pTab = pParse->pTriggerTab; 000343 } 000344 } 000345 #endif /* SQLITE_OMIT_TRIGGER */ 000346 #ifndef SQLITE_OMIT_UPSERT 000347 if( (pNC->ncFlags & NC_UUpsert)!=0 ){ 000348 Upsert *pUpsert = pNC->uNC.pUpsert; 000349 if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){ 000350 pTab = pUpsert->pUpsertSrc->a[0].pTab; 000351 pExpr->iTable = 2; 000352 } 000353 } 000354 #endif /* SQLITE_OMIT_UPSERT */ 000355 000356 if( pTab ){ 000357 int iCol; 000358 pSchema = pTab->pSchema; 000359 cntTab++; 000360 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ 000361 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ 000362 if( iCol==pTab->iPKey ){ 000363 iCol = -1; 000364 } 000365 break; 000366 } 000367 } 000368 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ 000369 /* IMP: R-51414-32910 */ 000370 iCol = -1; 000371 } 000372 if( iCol<pTab->nCol ){ 000373 cnt++; 000374 #ifndef SQLITE_OMIT_UPSERT 000375 if( pExpr->iTable==2 ){ 000376 testcase( iCol==(-1) ); 000377 if( IN_RENAME_OBJECT ){ 000378 pExpr->iColumn = iCol; 000379 pExpr->y.pTab = pTab; 000380 eNewExprOp = TK_COLUMN; 000381 }else{ 000382 pExpr->iTable = pNC->uNC.pUpsert->regData + iCol; 000383 eNewExprOp = TK_REGISTER; 000384 ExprSetProperty(pExpr, EP_Alias); 000385 } 000386 }else 000387 #endif /* SQLITE_OMIT_UPSERT */ 000388 { 000389 #ifndef SQLITE_OMIT_TRIGGER 000390 if( iCol<0 ){ 000391 pExpr->affExpr = SQLITE_AFF_INTEGER; 000392 }else if( pExpr->iTable==0 ){ 000393 testcase( iCol==31 ); 000394 testcase( iCol==32 ); 000395 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); 000396 }else{ 000397 testcase( iCol==31 ); 000398 testcase( iCol==32 ); 000399 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); 000400 } 000401 pExpr->y.pTab = pTab; 000402 pExpr->iColumn = (i16)iCol; 000403 eNewExprOp = TK_TRIGGER; 000404 #endif /* SQLITE_OMIT_TRIGGER */ 000405 } 000406 } 000407 } 000408 } 000409 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ 000410 000411 /* 000412 ** Perhaps the name is a reference to the ROWID 000413 */ 000414 if( cnt==0 000415 && cntTab==1 000416 && pMatch 000417 && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0 000418 && sqlite3IsRowid(zCol) 000419 && VisibleRowid(pMatch->pTab) 000420 ){ 000421 cnt = 1; 000422 pExpr->iColumn = -1; 000423 pExpr->affExpr = SQLITE_AFF_INTEGER; 000424 } 000425 000426 /* 000427 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z 000428 ** might refer to an result-set alias. This happens, for example, when 000429 ** we are resolving names in the WHERE clause of the following command: 000430 ** 000431 ** SELECT a+b AS x FROM table WHERE x<10; 000432 ** 000433 ** In cases like this, replace pExpr with a copy of the expression that 000434 ** forms the result set entry ("a+b" in the example) and return immediately. 000435 ** Note that the expression in the result set should have already been 000436 ** resolved by the time the WHERE clause is resolved. 000437 ** 000438 ** The ability to use an output result-set column in the WHERE, GROUP BY, 000439 ** or HAVING clauses, or as part of a larger expression in the ORDER BY 000440 ** clause is not standard SQL. This is a (goofy) SQLite extension, that 000441 ** is supported for backwards compatibility only. Hence, we issue a warning 000442 ** on sqlite3_log() whenever the capability is used. 000443 */ 000444 if( (pNC->ncFlags & NC_UEList)!=0 000445 && cnt==0 000446 && zTab==0 000447 ){ 000448 pEList = pNC->uNC.pEList; 000449 assert( pEList!=0 ); 000450 for(j=0; j<pEList->nExpr; j++){ 000451 char *zAs = pEList->a[j].zName; 000452 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 000453 Expr *pOrig; 000454 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 000455 assert( pExpr->x.pList==0 ); 000456 assert( pExpr->x.pSelect==0 ); 000457 pOrig = pEList->a[j].pExpr; 000458 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ 000459 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); 000460 return WRC_Abort; 000461 } 000462 if( ExprHasProperty(pOrig, EP_Win) 000463 && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC ) 000464 ){ 000465 sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs); 000466 return WRC_Abort; 000467 } 000468 if( sqlite3ExprVectorSize(pOrig)!=1 ){ 000469 sqlite3ErrorMsg(pParse, "row value misused"); 000470 return WRC_Abort; 000471 } 000472 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); 000473 cnt = 1; 000474 pMatch = 0; 000475 assert( zTab==0 && zDb==0 ); 000476 if( IN_RENAME_OBJECT ){ 000477 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); 000478 } 000479 goto lookupname_end; 000480 } 000481 } 000482 } 000483 000484 /* Advance to the next name context. The loop will exit when either 000485 ** we have a match (cnt>0) or when we run out of name contexts. 000486 */ 000487 if( cnt ) break; 000488 pNC = pNC->pNext; 000489 nSubquery++; 000490 }while( pNC ); 000491 000492 000493 /* 000494 ** If X and Y are NULL (in other words if only the column name Z is 000495 ** supplied) and the value of Z is enclosed in double-quotes, then 000496 ** Z is a string literal if it doesn't match any column names. In that 000497 ** case, we need to return right away and not make any changes to 000498 ** pExpr. 000499 ** 000500 ** Because no reference was made to outer contexts, the pNC->nRef 000501 ** fields are not changed in any context. 000502 */ 000503 if( cnt==0 && zTab==0 ){ 000504 assert( pExpr->op==TK_ID ); 000505 if( ExprHasProperty(pExpr,EP_DblQuoted) 000506 && areDoubleQuotedStringsEnabled(db, pTopNC) 000507 ){ 000508 /* If a double-quoted identifier does not match any known column name, 000509 ** then treat it as a string. 000510 ** 000511 ** This hack was added in the early days of SQLite in a misguided attempt 000512 ** to be compatible with MySQL 3.x, which used double-quotes for strings. 000513 ** I now sorely regret putting in this hack. The effect of this hack is 000514 ** that misspelled identifier names are silently converted into strings 000515 ** rather than causing an error, to the frustration of countless 000516 ** programmers. To all those frustrated programmers, my apologies. 000517 ** 000518 ** Someday, I hope to get rid of this hack. Unfortunately there is 000519 ** a huge amount of legacy SQL that uses it. So for now, we just 000520 ** issue a warning. 000521 */ 000522 sqlite3_log(SQLITE_WARNING, 000523 "double-quoted string literal: \"%w\"", zCol); 000524 #ifdef SQLITE_ENABLE_NORMALIZE 000525 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); 000526 #endif 000527 pExpr->op = TK_STRING; 000528 pExpr->y.pTab = 0; 000529 return WRC_Prune; 000530 } 000531 if( sqlite3ExprIdToTrueFalse(pExpr) ){ 000532 return WRC_Prune; 000533 } 000534 } 000535 000536 /* 000537 ** cnt==0 means there was not match. cnt>1 means there were two or 000538 ** more matches. Either way, we have an error. 000539 */ 000540 if( cnt!=1 ){ 000541 const char *zErr; 000542 zErr = cnt==0 ? "no such column" : "ambiguous column name"; 000543 if( zDb ){ 000544 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); 000545 }else if( zTab ){ 000546 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); 000547 }else{ 000548 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); 000549 } 000550 pParse->checkSchema = 1; 000551 pTopNC->nErr++; 000552 } 000553 000554 /* If a column from a table in pSrcList is referenced, then record 000555 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes 000556 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is 000557 ** set if the 63rd or any subsequent column is used. 000558 ** 000559 ** The colUsed mask is an optimization used to help determine if an 000560 ** index is a covering index. The correct answer is still obtained 000561 ** if the mask contains extra set bits. However, it is important to 000562 ** avoid setting bits beyond the maximum column number of the table. 000563 ** (See ticket [b92e5e8ec2cdbaa1]). 000564 ** 000565 ** If a generated column is referenced, set bits for every column 000566 ** of the table. 000567 */ 000568 if( pExpr->iColumn>=0 && pMatch!=0 ){ 000569 int n = pExpr->iColumn; 000570 Table *pExTab = pExpr->y.pTab; 000571 assert( pExTab!=0 ); 000572 assert( pMatch->iCursor==pExpr->iTable ); 000573 if( (pExTab->tabFlags & TF_HasGenerated)!=0 000574 && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0 000575 ){ 000576 testcase( pExTab->nCol==BMS-1 ); 000577 testcase( pExTab->nCol==BMS ); 000578 pMatch->colUsed = pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1; 000579 }else{ 000580 testcase( n==BMS-1 ); 000581 testcase( n==BMS ); 000582 if( n>=BMS ) n = BMS-1; 000583 pMatch->colUsed |= ((Bitmask)1)<<n; 000584 } 000585 } 000586 000587 /* Clean up and return 000588 */ 000589 sqlite3ExprDelete(db, pExpr->pLeft); 000590 pExpr->pLeft = 0; 000591 sqlite3ExprDelete(db, pExpr->pRight); 000592 pExpr->pRight = 0; 000593 pExpr->op = eNewExprOp; 000594 ExprSetProperty(pExpr, EP_Leaf); 000595 lookupname_end: 000596 if( cnt==1 ){ 000597 assert( pNC!=0 ); 000598 if( !ExprHasProperty(pExpr, EP_Alias) ){ 000599 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); 000600 } 000601 /* Increment the nRef value on all name contexts from TopNC up to 000602 ** the point where the name matched. */ 000603 for(;;){ 000604 assert( pTopNC!=0 ); 000605 pTopNC->nRef++; 000606 if( pTopNC==pNC ) break; 000607 pTopNC = pTopNC->pNext; 000608 } 000609 return WRC_Prune; 000610 } else { 000611 return WRC_Abort; 000612 } 000613 } 000614 000615 /* 000616 ** Allocate and return a pointer to an expression to load the column iCol 000617 ** from datasource iSrc in SrcList pSrc. 000618 */ 000619 Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ 000620 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); 000621 if( p ){ 000622 struct SrcList_item *pItem = &pSrc->a[iSrc]; 000623 Table *pTab = p->y.pTab = pItem->pTab; 000624 p->iTable = pItem->iCursor; 000625 if( p->y.pTab->iPKey==iCol ){ 000626 p->iColumn = -1; 000627 }else{ 000628 p->iColumn = (ynVar)iCol; 000629 if( (pTab->tabFlags & TF_HasGenerated)!=0 000630 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0 000631 ){ 000632 testcase( pTab->nCol==63 ); 000633 testcase( pTab->nCol==64 ); 000634 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1; 000635 }else{ 000636 testcase( iCol==BMS ); 000637 testcase( iCol==BMS-1 ); 000638 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); 000639 } 000640 } 000641 } 000642 return p; 000643 } 000644 000645 /* 000646 ** Report an error that an expression is not valid for some set of 000647 ** pNC->ncFlags values determined by validMask. 000648 ** 000649 ** static void notValid( 000650 ** Parse *pParse, // Leave error message here 000651 ** NameContext *pNC, // The name context 000652 ** const char *zMsg, // Type of error 000653 ** int validMask, // Set of contexts for which prohibited 000654 ** Expr *pExpr // Invalidate this expression on error 000655 ** ){...} 000656 ** 000657 ** As an optimization, since the conditional is almost always false 000658 ** (because errors are rare), the conditional is moved outside of the 000659 ** function call using a macro. 000660 */ 000661 static void notValidImpl( 000662 Parse *pParse, /* Leave error message here */ 000663 NameContext *pNC, /* The name context */ 000664 const char *zMsg, /* Type of error */ 000665 Expr *pExpr /* Invalidate this expression on error */ 000666 ){ 000667 const char *zIn = "partial index WHERE clauses"; 000668 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions"; 000669 #ifndef SQLITE_OMIT_CHECK 000670 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints"; 000671 #endif 000672 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 000673 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns"; 000674 #endif 000675 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); 000676 if( pExpr ) pExpr->op = TK_NULL; 000677 } 000678 #define sqlite3ResolveNotValid(P,N,M,X,E) \ 000679 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \ 000680 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E); 000681 000682 /* 000683 ** Expression p should encode a floating point value between 1.0 and 0.0. 000684 ** Return 1024 times this value. Or return -1 if p is not a floating point 000685 ** value between 1.0 and 0.0. 000686 */ 000687 static int exprProbability(Expr *p){ 000688 double r = -1.0; 000689 if( p->op!=TK_FLOAT ) return -1; 000690 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); 000691 assert( r>=0.0 ); 000692 if( r>1.0 ) return -1; 000693 return (int)(r*134217728.0); 000694 } 000695 000696 /* 000697 ** This routine is callback for sqlite3WalkExpr(). 000698 ** 000699 ** Resolve symbolic names into TK_COLUMN operators for the current 000700 ** node in the expression tree. Return 0 to continue the search down 000701 ** the tree or 2 to abort the tree walk. 000702 ** 000703 ** This routine also does error checking and name resolution for 000704 ** function names. The operator for aggregate functions is changed 000705 ** to TK_AGG_FUNCTION. 000706 */ 000707 static int resolveExprStep(Walker *pWalker, Expr *pExpr){ 000708 NameContext *pNC; 000709 Parse *pParse; 000710 000711 pNC = pWalker->u.pNC; 000712 assert( pNC!=0 ); 000713 pParse = pNC->pParse; 000714 assert( pParse==pWalker->pParse ); 000715 000716 #ifndef NDEBUG 000717 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ 000718 SrcList *pSrcList = pNC->pSrcList; 000719 int i; 000720 for(i=0; i<pNC->pSrcList->nSrc; i++){ 000721 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab); 000722 } 000723 } 000724 #endif 000725 switch( pExpr->op ){ 000726 000727 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) 000728 /* The special operator TK_ROW means use the rowid for the first 000729 ** column in the FROM clause. This is used by the LIMIT and ORDER BY 000730 ** clause processing on UPDATE and DELETE statements. 000731 */ 000732 case TK_ROW: { 000733 SrcList *pSrcList = pNC->pSrcList; 000734 struct SrcList_item *pItem; 000735 assert( pSrcList && pSrcList->nSrc==1 ); 000736 pItem = pSrcList->a; 000737 assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 ); 000738 pExpr->op = TK_COLUMN; 000739 pExpr->y.pTab = pItem->pTab; 000740 pExpr->iTable = pItem->iCursor; 000741 pExpr->iColumn = -1; 000742 pExpr->affExpr = SQLITE_AFF_INTEGER; 000743 break; 000744 } 000745 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) 000746 && !defined(SQLITE_OMIT_SUBQUERY) */ 000747 000748 /* A column name: ID 000749 ** Or table name and column name: ID.ID 000750 ** Or a database, table and column: ID.ID.ID 000751 ** 000752 ** The TK_ID and TK_OUT cases are combined so that there will only 000753 ** be one call to lookupName(). Then the compiler will in-line 000754 ** lookupName() for a size reduction and performance increase. 000755 */ 000756 case TK_ID: 000757 case TK_DOT: { 000758 const char *zColumn; 000759 const char *zTable; 000760 const char *zDb; 000761 Expr *pRight; 000762 000763 if( pExpr->op==TK_ID ){ 000764 zDb = 0; 000765 zTable = 0; 000766 zColumn = pExpr->u.zToken; 000767 }else{ 000768 Expr *pLeft = pExpr->pLeft; 000769 testcase( pNC->ncFlags & NC_IdxExpr ); 000770 testcase( pNC->ncFlags & NC_GenCol ); 000771 sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator", 000772 NC_IdxExpr|NC_GenCol, 0); 000773 pRight = pExpr->pRight; 000774 if( pRight->op==TK_ID ){ 000775 zDb = 0; 000776 }else{ 000777 assert( pRight->op==TK_DOT ); 000778 zDb = pLeft->u.zToken; 000779 pLeft = pRight->pLeft; 000780 pRight = pRight->pRight; 000781 } 000782 zTable = pLeft->u.zToken; 000783 zColumn = pRight->u.zToken; 000784 if( IN_RENAME_OBJECT ){ 000785 sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight); 000786 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft); 000787 } 000788 } 000789 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr); 000790 } 000791 000792 /* Resolve function names 000793 */ 000794 case TK_FUNCTION: { 000795 ExprList *pList = pExpr->x.pList; /* The argument list */ 000796 int n = pList ? pList->nExpr : 0; /* Number of arguments */ 000797 int no_such_func = 0; /* True if no such function exists */ 000798 int wrong_num_args = 0; /* True if wrong number of arguments */ 000799 int is_agg = 0; /* True if is an aggregate function */ 000800 int nId; /* Number of characters in function name */ 000801 const char *zId; /* The function name. */ 000802 FuncDef *pDef; /* Information about the function */ 000803 u8 enc = ENC(pParse->db); /* The database encoding */ 000804 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin)); 000805 #ifndef SQLITE_OMIT_WINDOWFUNC 000806 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0); 000807 #endif 000808 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 000809 zId = pExpr->u.zToken; 000810 nId = sqlite3Strlen30(zId); 000811 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0); 000812 if( pDef==0 ){ 000813 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0); 000814 if( pDef==0 ){ 000815 no_such_func = 1; 000816 }else{ 000817 wrong_num_args = 1; 000818 } 000819 }else{ 000820 is_agg = pDef->xFinalize!=0; 000821 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ 000822 ExprSetProperty(pExpr, EP_Unlikely); 000823 if( n==2 ){ 000824 pExpr->iTable = exprProbability(pList->a[1].pExpr); 000825 if( pExpr->iTable<0 ){ 000826 sqlite3ErrorMsg(pParse, 000827 "second argument to likelihood() must be a " 000828 "constant between 0.0 and 1.0"); 000829 pNC->nErr++; 000830 } 000831 }else{ 000832 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is 000833 ** equivalent to likelihood(X, 0.0625). 000834 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is 000835 ** short-hand for likelihood(X,0.0625). 000836 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand 000837 ** for likelihood(X,0.9375). 000838 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent 000839 ** to likelihood(X,0.9375). */ 000840 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */ 000841 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120; 000842 } 000843 } 000844 #ifndef SQLITE_OMIT_AUTHORIZATION 000845 { 000846 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); 000847 if( auth!=SQLITE_OK ){ 000848 if( auth==SQLITE_DENY ){ 000849 sqlite3ErrorMsg(pParse, "not authorized to use function: %s", 000850 pDef->zName); 000851 pNC->nErr++; 000852 } 000853 pExpr->op = TK_NULL; 000854 return WRC_Prune; 000855 } 000856 } 000857 #endif 000858 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ 000859 /* For the purposes of the EP_ConstFunc flag, date and time 000860 ** functions and other functions that change slowly are considered 000861 ** constant because they are constant for the duration of one query. 000862 ** This allows them to be factored out of inner loops. */ 000863 ExprSetProperty(pExpr,EP_ConstFunc); 000864 } 000865 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ 000866 /* Date/time functions that use 'now', and other functions like 000867 ** sqlite_version() that might change over time cannot be used 000868 ** in an index. */ 000869 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions", 000870 NC_SelfRef, 0); 000871 }else{ 000872 assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */ 000873 pExpr->op2 = pNC->ncFlags & NC_SelfRef; 000874 } 000875 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 000876 && pParse->nested==0 000877 && sqlite3Config.bInternalFunctions==0 000878 ){ 000879 /* Internal-use-only functions are disallowed unless the 000880 ** SQL is being compiled using sqlite3NestedParse() */ 000881 no_such_func = 1; 000882 pDef = 0; 000883 }else 000884 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0 000885 && ExprHasProperty(pExpr, EP_Indirect) 000886 && !IN_RENAME_OBJECT 000887 ){ 000888 /* Functions tagged with SQLITE_DIRECTONLY may not be used 000889 ** inside of triggers and views */ 000890 sqlite3ErrorMsg(pParse, "%s() prohibited in triggers and views", 000891 pDef->zName); 000892 } 000893 } 000894 000895 if( 0==IN_RENAME_OBJECT ){ 000896 #ifndef SQLITE_OMIT_WINDOWFUNC 000897 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX) 000898 || (pDef->xValue==0 && pDef->xInverse==0) 000899 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize) 000900 ); 000901 if( pDef && pDef->xValue==0 && pWin ){ 000902 sqlite3ErrorMsg(pParse, 000903 "%.*s() may not be used as a window function", nId, zId 000904 ); 000905 pNC->nErr++; 000906 }else if( 000907 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) 000908 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin) 000909 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0) 000910 ){ 000911 const char *zType; 000912 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){ 000913 zType = "window"; 000914 }else{ 000915 zType = "aggregate"; 000916 } 000917 sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId); 000918 pNC->nErr++; 000919 is_agg = 0; 000920 } 000921 #else 000922 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){ 000923 sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId); 000924 pNC->nErr++; 000925 is_agg = 0; 000926 } 000927 #endif 000928 else if( no_such_func && pParse->db->init.busy==0 000929 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 000930 && pParse->explain==0 000931 #endif 000932 ){ 000933 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId); 000934 pNC->nErr++; 000935 }else if( wrong_num_args ){ 000936 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()", 000937 nId, zId); 000938 pNC->nErr++; 000939 } 000940 #ifndef SQLITE_OMIT_WINDOWFUNC 000941 else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){ 000942 sqlite3ErrorMsg(pParse, 000943 "FILTER may not be used with non-aggregate %.*s()", 000944 nId, zId 000945 ); 000946 pNC->nErr++; 000947 } 000948 #endif 000949 if( is_agg ){ 000950 /* Window functions may not be arguments of aggregate functions. 000951 ** Or arguments of other window functions. But aggregate functions 000952 ** may be arguments for window functions. */ 000953 #ifndef SQLITE_OMIT_WINDOWFUNC 000954 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0)); 000955 #else 000956 pNC->ncFlags &= ~NC_AllowAgg; 000957 #endif 000958 } 000959 } 000960 #ifndef SQLITE_OMIT_WINDOWFUNC 000961 else if( ExprHasProperty(pExpr, EP_WinFunc) ){ 000962 is_agg = 1; 000963 } 000964 #endif 000965 sqlite3WalkExprList(pWalker, pList); 000966 if( is_agg ){ 000967 #ifndef SQLITE_OMIT_WINDOWFUNC 000968 if( pWin ){ 000969 Select *pSel = pNC->pWinSelect; 000970 assert( pWin==pExpr->y.pWin ); 000971 if( IN_RENAME_OBJECT==0 ){ 000972 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef); 000973 } 000974 sqlite3WalkExprList(pWalker, pWin->pPartition); 000975 sqlite3WalkExprList(pWalker, pWin->pOrderBy); 000976 sqlite3WalkExpr(pWalker, pWin->pFilter); 000977 sqlite3WindowLink(pSel, pWin); 000978 pNC->ncFlags |= NC_HasWin; 000979 }else 000980 #endif /* SQLITE_OMIT_WINDOWFUNC */ 000981 { 000982 NameContext *pNC2 = pNC; 000983 pExpr->op = TK_AGG_FUNCTION; 000984 pExpr->op2 = 0; 000985 #ifndef SQLITE_OMIT_WINDOWFUNC 000986 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 000987 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter); 000988 } 000989 #endif 000990 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){ 000991 pExpr->op2++; 000992 pNC2 = pNC2->pNext; 000993 } 000994 assert( pDef!=0 || IN_RENAME_OBJECT ); 000995 if( pNC2 && pDef ){ 000996 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); 000997 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); 000998 pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX); 000999 001000 } 001001 } 001002 pNC->ncFlags |= savedAllowFlags; 001003 } 001004 /* FIX ME: Compute pExpr->affinity based on the expected return 001005 ** type of the function 001006 */ 001007 return WRC_Prune; 001008 } 001009 #ifndef SQLITE_OMIT_SUBQUERY 001010 case TK_SELECT: 001011 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); 001012 #endif 001013 case TK_IN: { 001014 testcase( pExpr->op==TK_IN ); 001015 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 001016 int nRef = pNC->nRef; 001017 testcase( pNC->ncFlags & NC_IsCheck ); 001018 testcase( pNC->ncFlags & NC_PartIdx ); 001019 testcase( pNC->ncFlags & NC_IdxExpr ); 001020 testcase( pNC->ncFlags & NC_GenCol ); 001021 sqlite3ResolveNotValid(pParse, pNC, "subqueries", 001022 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr); 001023 sqlite3WalkSelect(pWalker, pExpr->x.pSelect); 001024 assert( pNC->nRef>=nRef ); 001025 if( nRef!=pNC->nRef ){ 001026 ExprSetProperty(pExpr, EP_VarSelect); 001027 pNC->ncFlags |= NC_VarSelect; 001028 } 001029 } 001030 break; 001031 } 001032 case TK_VARIABLE: { 001033 testcase( pNC->ncFlags & NC_IsCheck ); 001034 testcase( pNC->ncFlags & NC_PartIdx ); 001035 testcase( pNC->ncFlags & NC_IdxExpr ); 001036 testcase( pNC->ncFlags & NC_GenCol ); 001037 sqlite3ResolveNotValid(pParse, pNC, "parameters", 001038 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr); 001039 break; 001040 } 001041 case TK_IS: 001042 case TK_ISNOT: { 001043 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight); 001044 assert( !ExprHasProperty(pExpr, EP_Reduced) ); 001045 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE", 001046 ** and "x IS NOT FALSE". */ 001047 if( pRight->op==TK_ID ){ 001048 int rc = resolveExprStep(pWalker, pRight); 001049 if( rc==WRC_Abort ) return WRC_Abort; 001050 if( pRight->op==TK_TRUEFALSE ){ 001051 pExpr->op2 = pExpr->op; 001052 pExpr->op = TK_TRUTH; 001053 return WRC_Continue; 001054 } 001055 } 001056 /* Fall thru */ 001057 } 001058 case TK_BETWEEN: 001059 case TK_EQ: 001060 case TK_NE: 001061 case TK_LT: 001062 case TK_LE: 001063 case TK_GT: 001064 case TK_GE: { 001065 int nLeft, nRight; 001066 if( pParse->db->mallocFailed ) break; 001067 assert( pExpr->pLeft!=0 ); 001068 nLeft = sqlite3ExprVectorSize(pExpr->pLeft); 001069 if( pExpr->op==TK_BETWEEN ){ 001070 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr); 001071 if( nRight==nLeft ){ 001072 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr); 001073 } 001074 }else{ 001075 assert( pExpr->pRight!=0 ); 001076 nRight = sqlite3ExprVectorSize(pExpr->pRight); 001077 } 001078 if( nLeft!=nRight ){ 001079 testcase( pExpr->op==TK_EQ ); 001080 testcase( pExpr->op==TK_NE ); 001081 testcase( pExpr->op==TK_LT ); 001082 testcase( pExpr->op==TK_LE ); 001083 testcase( pExpr->op==TK_GT ); 001084 testcase( pExpr->op==TK_GE ); 001085 testcase( pExpr->op==TK_IS ); 001086 testcase( pExpr->op==TK_ISNOT ); 001087 testcase( pExpr->op==TK_BETWEEN ); 001088 sqlite3ErrorMsg(pParse, "row value misused"); 001089 } 001090 break; 001091 } 001092 } 001093 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue; 001094 } 001095 001096 /* 001097 ** pEList is a list of expressions which are really the result set of the 001098 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. 001099 ** This routine checks to see if pE is a simple identifier which corresponds 001100 ** to the AS-name of one of the terms of the expression list. If it is, 001101 ** this routine return an integer between 1 and N where N is the number of 001102 ** elements in pEList, corresponding to the matching entry. If there is 001103 ** no match, or if pE is not a simple identifier, then this routine 001104 ** return 0. 001105 ** 001106 ** pEList has been resolved. pE has not. 001107 */ 001108 static int resolveAsName( 001109 Parse *pParse, /* Parsing context for error messages */ 001110 ExprList *pEList, /* List of expressions to scan */ 001111 Expr *pE /* Expression we are trying to match */ 001112 ){ 001113 int i; /* Loop counter */ 001114 001115 UNUSED_PARAMETER(pParse); 001116 001117 if( pE->op==TK_ID ){ 001118 char *zCol = pE->u.zToken; 001119 for(i=0; i<pEList->nExpr; i++){ 001120 char *zAs = pEList->a[i].zName; 001121 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ 001122 return i+1; 001123 } 001124 } 001125 } 001126 return 0; 001127 } 001128 001129 /* 001130 ** pE is a pointer to an expression which is a single term in the 001131 ** ORDER BY of a compound SELECT. The expression has not been 001132 ** name resolved. 001133 ** 001134 ** At the point this routine is called, we already know that the 001135 ** ORDER BY term is not an integer index into the result set. That 001136 ** case is handled by the calling routine. 001137 ** 001138 ** Attempt to match pE against result set columns in the left-most 001139 ** SELECT statement. Return the index i of the matching column, 001140 ** as an indication to the caller that it should sort by the i-th column. 001141 ** The left-most column is 1. In other words, the value returned is the 001142 ** same integer value that would be used in the SQL statement to indicate 001143 ** the column. 001144 ** 001145 ** If there is no match, return 0. Return -1 if an error occurs. 001146 */ 001147 static int resolveOrderByTermToExprList( 001148 Parse *pParse, /* Parsing context for error messages */ 001149 Select *pSelect, /* The SELECT statement with the ORDER BY clause */ 001150 Expr *pE /* The specific ORDER BY term */ 001151 ){ 001152 int i; /* Loop counter */ 001153 ExprList *pEList; /* The columns of the result set */ 001154 NameContext nc; /* Name context for resolving pE */ 001155 sqlite3 *db; /* Database connection */ 001156 int rc; /* Return code from subprocedures */ 001157 u8 savedSuppErr; /* Saved value of db->suppressErr */ 001158 001159 assert( sqlite3ExprIsInteger(pE, &i)==0 ); 001160 pEList = pSelect->pEList; 001161 001162 /* Resolve all names in the ORDER BY term expression 001163 */ 001164 memset(&nc, 0, sizeof(nc)); 001165 nc.pParse = pParse; 001166 nc.pSrcList = pSelect->pSrc; 001167 nc.uNC.pEList = pEList; 001168 nc.ncFlags = NC_AllowAgg|NC_UEList; 001169 nc.nErr = 0; 001170 db = pParse->db; 001171 savedSuppErr = db->suppressErr; 001172 db->suppressErr = 1; 001173 rc = sqlite3ResolveExprNames(&nc, pE); 001174 db->suppressErr = savedSuppErr; 001175 if( rc ) return 0; 001176 001177 /* Try to match the ORDER BY expression against an expression 001178 ** in the result set. Return an 1-based index of the matching 001179 ** result-set entry. 001180 */ 001181 for(i=0; i<pEList->nExpr; i++){ 001182 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){ 001183 return i+1; 001184 } 001185 } 001186 001187 /* If no match, return 0. */ 001188 return 0; 001189 } 001190 001191 /* 001192 ** Generate an ORDER BY or GROUP BY term out-of-range error. 001193 */ 001194 static void resolveOutOfRangeError( 001195 Parse *pParse, /* The error context into which to write the error */ 001196 const char *zType, /* "ORDER" or "GROUP" */ 001197 int i, /* The index (1-based) of the term out of range */ 001198 int mx /* Largest permissible value of i */ 001199 ){ 001200 sqlite3ErrorMsg(pParse, 001201 "%r %s BY term out of range - should be " 001202 "between 1 and %d", i, zType, mx); 001203 } 001204 001205 /* 001206 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify 001207 ** each term of the ORDER BY clause is a constant integer between 1 001208 ** and N where N is the number of columns in the compound SELECT. 001209 ** 001210 ** ORDER BY terms that are already an integer between 1 and N are 001211 ** unmodified. ORDER BY terms that are integers outside the range of 001212 ** 1 through N generate an error. ORDER BY terms that are expressions 001213 ** are matched against result set expressions of compound SELECT 001214 ** beginning with the left-most SELECT and working toward the right. 001215 ** At the first match, the ORDER BY expression is transformed into 001216 ** the integer column number. 001217 ** 001218 ** Return the number of errors seen. 001219 */ 001220 static int resolveCompoundOrderBy( 001221 Parse *pParse, /* Parsing context. Leave error messages here */ 001222 Select *pSelect /* The SELECT statement containing the ORDER BY */ 001223 ){ 001224 int i; 001225 ExprList *pOrderBy; 001226 ExprList *pEList; 001227 sqlite3 *db; 001228 int moreToDo = 1; 001229 001230 pOrderBy = pSelect->pOrderBy; 001231 if( pOrderBy==0 ) return 0; 001232 db = pParse->db; 001233 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 001234 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); 001235 return 1; 001236 } 001237 for(i=0; i<pOrderBy->nExpr; i++){ 001238 pOrderBy->a[i].done = 0; 001239 } 001240 pSelect->pNext = 0; 001241 while( pSelect->pPrior ){ 001242 pSelect->pPrior->pNext = pSelect; 001243 pSelect = pSelect->pPrior; 001244 } 001245 while( pSelect && moreToDo ){ 001246 struct ExprList_item *pItem; 001247 moreToDo = 0; 001248 pEList = pSelect->pEList; 001249 assert( pEList!=0 ); 001250 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 001251 int iCol = -1; 001252 Expr *pE, *pDup; 001253 if( pItem->done ) continue; 001254 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr); 001255 if( sqlite3ExprIsInteger(pE, &iCol) ){ 001256 if( iCol<=0 || iCol>pEList->nExpr ){ 001257 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr); 001258 return 1; 001259 } 001260 }else{ 001261 iCol = resolveAsName(pParse, pEList, pE); 001262 if( iCol==0 ){ 001263 /* Now test if expression pE matches one of the values returned 001264 ** by pSelect. In the usual case this is done by duplicating the 001265 ** expression, resolving any symbols in it, and then comparing 001266 ** it against each expression returned by the SELECT statement. 001267 ** Once the comparisons are finished, the duplicate expression 001268 ** is deleted. 001269 ** 001270 ** Or, if this is running as part of an ALTER TABLE operation, 001271 ** resolve the symbols in the actual expression, not a duplicate. 001272 ** And, if one of the comparisons is successful, leave the expression 001273 ** as is instead of transforming it to an integer as in the usual 001274 ** case. This allows the code in alter.c to modify column 001275 ** refererences within the ORDER BY expression as required. */ 001276 if( IN_RENAME_OBJECT ){ 001277 pDup = pE; 001278 }else{ 001279 pDup = sqlite3ExprDup(db, pE, 0); 001280 } 001281 if( !db->mallocFailed ){ 001282 assert(pDup); 001283 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); 001284 } 001285 if( !IN_RENAME_OBJECT ){ 001286 sqlite3ExprDelete(db, pDup); 001287 } 001288 } 001289 } 001290 if( iCol>0 ){ 001291 /* Convert the ORDER BY term into an integer column number iCol, 001292 ** taking care to preserve the COLLATE clause if it exists */ 001293 if( !IN_RENAME_OBJECT ){ 001294 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 001295 if( pNew==0 ) return 1; 001296 pNew->flags |= EP_IntValue; 001297 pNew->u.iValue = iCol; 001298 if( pItem->pExpr==pE ){ 001299 pItem->pExpr = pNew; 001300 }else{ 001301 Expr *pParent = pItem->pExpr; 001302 assert( pParent->op==TK_COLLATE ); 001303 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft; 001304 assert( pParent->pLeft==pE ); 001305 pParent->pLeft = pNew; 001306 } 001307 sqlite3ExprDelete(db, pE); 001308 pItem->u.x.iOrderByCol = (u16)iCol; 001309 } 001310 pItem->done = 1; 001311 }else{ 001312 moreToDo = 1; 001313 } 001314 } 001315 pSelect = pSelect->pNext; 001316 } 001317 for(i=0; i<pOrderBy->nExpr; i++){ 001318 if( pOrderBy->a[i].done==0 ){ 001319 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " 001320 "column in the result set", i+1); 001321 return 1; 001322 } 001323 } 001324 return 0; 001325 } 001326 001327 /* 001328 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of 001329 ** the SELECT statement pSelect. If any term is reference to a 001330 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol 001331 ** field) then convert that term into a copy of the corresponding result set 001332 ** column. 001333 ** 001334 ** If any errors are detected, add an error message to pParse and 001335 ** return non-zero. Return zero if no errors are seen. 001336 */ 001337 int sqlite3ResolveOrderGroupBy( 001338 Parse *pParse, /* Parsing context. Leave error messages here */ 001339 Select *pSelect, /* The SELECT statement containing the clause */ 001340 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 001341 const char *zType /* "ORDER" or "GROUP" */ 001342 ){ 001343 int i; 001344 sqlite3 *db = pParse->db; 001345 ExprList *pEList; 001346 struct ExprList_item *pItem; 001347 001348 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0; 001349 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 001350 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 001351 return 1; 001352 } 001353 pEList = pSelect->pEList; 001354 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ 001355 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 001356 if( pItem->u.x.iOrderByCol ){ 001357 if( pItem->u.x.iOrderByCol>pEList->nExpr ){ 001358 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr); 001359 return 1; 001360 } 001361 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, 001362 zType,0); 001363 } 001364 } 001365 return 0; 001366 } 001367 001368 #ifndef SQLITE_OMIT_WINDOWFUNC 001369 /* 001370 ** Walker callback for windowRemoveExprFromSelect(). 001371 */ 001372 static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){ 001373 UNUSED_PARAMETER(pWalker); 001374 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 001375 Window *pWin = pExpr->y.pWin; 001376 sqlite3WindowUnlinkFromSelect(pWin); 001377 } 001378 return WRC_Continue; 001379 } 001380 001381 /* 001382 ** Remove any Window objects owned by the expression pExpr from the 001383 ** Select.pWin list of Select object pSelect. 001384 */ 001385 static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){ 001386 if( pSelect->pWin ){ 001387 Walker sWalker; 001388 memset(&sWalker, 0, sizeof(Walker)); 001389 sWalker.xExprCallback = resolveRemoveWindowsCb; 001390 sWalker.u.pSelect = pSelect; 001391 sqlite3WalkExpr(&sWalker, pExpr); 001392 } 001393 } 001394 #else 001395 # define windowRemoveExprFromSelect(a, b) 001396 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001397 001398 /* 001399 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. 001400 ** The Name context of the SELECT statement is pNC. zType is either 001401 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. 001402 ** 001403 ** This routine resolves each term of the clause into an expression. 001404 ** If the order-by term is an integer I between 1 and N (where N is the 001405 ** number of columns in the result set of the SELECT) then the expression 001406 ** in the resolution is a copy of the I-th result-set expression. If 001407 ** the order-by term is an identifier that corresponds to the AS-name of 001408 ** a result-set expression, then the term resolves to a copy of the 001409 ** result-set expression. Otherwise, the expression is resolved in 001410 ** the usual way - using sqlite3ResolveExprNames(). 001411 ** 001412 ** This routine returns the number of errors. If errors occur, then 001413 ** an appropriate error message might be left in pParse. (OOM errors 001414 ** excepted.) 001415 */ 001416 static int resolveOrderGroupBy( 001417 NameContext *pNC, /* The name context of the SELECT statement */ 001418 Select *pSelect, /* The SELECT statement holding pOrderBy */ 001419 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ 001420 const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 001421 ){ 001422 int i, j; /* Loop counters */ 001423 int iCol; /* Column number */ 001424 struct ExprList_item *pItem; /* A term of the ORDER BY clause */ 001425 Parse *pParse; /* Parsing context */ 001426 int nResult; /* Number of terms in the result set */ 001427 001428 if( pOrderBy==0 ) return 0; 001429 nResult = pSelect->pEList->nExpr; 001430 pParse = pNC->pParse; 001431 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 001432 Expr *pE = pItem->pExpr; 001433 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE); 001434 if( zType[0]!='G' ){ 001435 iCol = resolveAsName(pParse, pSelect->pEList, pE2); 001436 if( iCol>0 ){ 001437 /* If an AS-name match is found, mark this ORDER BY column as being 001438 ** a copy of the iCol-th result-set column. The subsequent call to 001439 ** sqlite3ResolveOrderGroupBy() will convert the expression to a 001440 ** copy of the iCol-th result-set expression. */ 001441 pItem->u.x.iOrderByCol = (u16)iCol; 001442 continue; 001443 } 001444 } 001445 if( sqlite3ExprIsInteger(pE2, &iCol) ){ 001446 /* The ORDER BY term is an integer constant. Again, set the column 001447 ** number so that sqlite3ResolveOrderGroupBy() will convert the 001448 ** order-by term to a copy of the result-set expression */ 001449 if( iCol<1 || iCol>0xffff ){ 001450 resolveOutOfRangeError(pParse, zType, i+1, nResult); 001451 return 1; 001452 } 001453 pItem->u.x.iOrderByCol = (u16)iCol; 001454 continue; 001455 } 001456 001457 /* Otherwise, treat the ORDER BY term as an ordinary expression */ 001458 pItem->u.x.iOrderByCol = 0; 001459 if( sqlite3ResolveExprNames(pNC, pE) ){ 001460 return 1; 001461 } 001462 for(j=0; j<pSelect->pEList->nExpr; j++){ 001463 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ 001464 /* Since this expresion is being changed into a reference 001465 ** to an identical expression in the result set, remove all Window 001466 ** objects belonging to the expression from the Select.pWin list. */ 001467 windowRemoveExprFromSelect(pSelect, pE); 001468 pItem->u.x.iOrderByCol = j+1; 001469 } 001470 } 001471 } 001472 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); 001473 } 001474 001475 /* 001476 ** Resolve names in the SELECT statement p and all of its descendants. 001477 */ 001478 static int resolveSelectStep(Walker *pWalker, Select *p){ 001479 NameContext *pOuterNC; /* Context that contains this SELECT */ 001480 NameContext sNC; /* Name context of this SELECT */ 001481 int isCompound; /* True if p is a compound select */ 001482 int nCompound; /* Number of compound terms processed so far */ 001483 Parse *pParse; /* Parsing context */ 001484 int i; /* Loop counter */ 001485 ExprList *pGroupBy; /* The GROUP BY clause */ 001486 Select *pLeftmost; /* Left-most of SELECT of a compound */ 001487 sqlite3 *db; /* Database connection */ 001488 001489 001490 assert( p!=0 ); 001491 if( p->selFlags & SF_Resolved ){ 001492 return WRC_Prune; 001493 } 001494 pOuterNC = pWalker->u.pNC; 001495 pParse = pWalker->pParse; 001496 db = pParse->db; 001497 001498 /* Normally sqlite3SelectExpand() will be called first and will have 001499 ** already expanded this SELECT. However, if this is a subquery within 001500 ** an expression, sqlite3ResolveExprNames() will be called without a 001501 ** prior call to sqlite3SelectExpand(). When that happens, let 001502 ** sqlite3SelectPrep() do all of the processing for this SELECT. 001503 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and 001504 ** this routine in the correct order. 001505 */ 001506 if( (p->selFlags & SF_Expanded)==0 ){ 001507 sqlite3SelectPrep(pParse, p, pOuterNC); 001508 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune; 001509 } 001510 001511 isCompound = p->pPrior!=0; 001512 nCompound = 0; 001513 pLeftmost = p; 001514 while( p ){ 001515 assert( (p->selFlags & SF_Expanded)!=0 ); 001516 assert( (p->selFlags & SF_Resolved)==0 ); 001517 p->selFlags |= SF_Resolved; 001518 001519 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 001520 ** are not allowed to refer to any names, so pass an empty NameContext. 001521 */ 001522 memset(&sNC, 0, sizeof(sNC)); 001523 sNC.pParse = pParse; 001524 sNC.pWinSelect = p; 001525 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){ 001526 return WRC_Abort; 001527 } 001528 001529 /* If the SF_Converted flags is set, then this Select object was 001530 ** was created by the convertCompoundSelectToSubquery() function. 001531 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved 001532 ** as if it were part of the sub-query, not the parent. This block 001533 ** moves the pOrderBy down to the sub-query. It will be moved back 001534 ** after the names have been resolved. */ 001535 if( p->selFlags & SF_Converted ){ 001536 Select *pSub = p->pSrc->a[0].pSelect; 001537 assert( p->pSrc->nSrc==1 && p->pOrderBy ); 001538 assert( pSub->pPrior && pSub->pOrderBy==0 ); 001539 pSub->pOrderBy = p->pOrderBy; 001540 p->pOrderBy = 0; 001541 } 001542 001543 /* Recursively resolve names in all subqueries 001544 */ 001545 for(i=0; i<p->pSrc->nSrc; i++){ 001546 struct SrcList_item *pItem = &p->pSrc->a[i]; 001547 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){ 001548 NameContext *pNC; /* Used to iterate name contexts */ 001549 int nRef = 0; /* Refcount for pOuterNC and outer contexts */ 001550 const char *zSavedContext = pParse->zAuthContext; 001551 001552 /* Count the total number of references to pOuterNC and all of its 001553 ** parent contexts. After resolving references to expressions in 001554 ** pItem->pSelect, check if this value has changed. If so, then 001555 ** SELECT statement pItem->pSelect must be correlated. Set the 001556 ** pItem->fg.isCorrelated flag if this is the case. */ 001557 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef; 001558 001559 if( pItem->zName ) pParse->zAuthContext = pItem->zName; 001560 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); 001561 pParse->zAuthContext = zSavedContext; 001562 if( pParse->nErr || db->mallocFailed ) return WRC_Abort; 001563 001564 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef; 001565 assert( pItem->fg.isCorrelated==0 && nRef<=0 ); 001566 pItem->fg.isCorrelated = (nRef!=0); 001567 } 001568 } 001569 001570 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to 001571 ** resolve the result-set expression list. 001572 */ 001573 sNC.ncFlags = NC_AllowAgg|NC_AllowWin; 001574 sNC.pSrcList = p->pSrc; 001575 sNC.pNext = pOuterNC; 001576 001577 /* Resolve names in the result set. */ 001578 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; 001579 sNC.ncFlags &= ~NC_AllowWin; 001580 001581 /* If there are no aggregate functions in the result-set, and no GROUP BY 001582 ** expression, do not allow aggregates in any of the other expressions. 001583 */ 001584 assert( (p->selFlags & SF_Aggregate)==0 ); 001585 pGroupBy = p->pGroupBy; 001586 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){ 001587 assert( NC_MinMaxAgg==SF_MinMaxAgg ); 001588 p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg); 001589 }else{ 001590 sNC.ncFlags &= ~NC_AllowAgg; 001591 } 001592 001593 /* If a HAVING clause is present, then there must be a GROUP BY clause. 001594 */ 001595 if( p->pHaving && !pGroupBy ){ 001596 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING"); 001597 return WRC_Abort; 001598 } 001599 001600 /* Add the output column list to the name-context before parsing the 001601 ** other expressions in the SELECT statement. This is so that 001602 ** expressions in the WHERE clause (etc.) can refer to expressions by 001603 ** aliases in the result set. 001604 ** 001605 ** Minor point: If this is the case, then the expression will be 001606 ** re-evaluated for each reference to it. 001607 */ 001608 assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 ); 001609 sNC.uNC.pEList = p->pEList; 001610 sNC.ncFlags |= NC_UEList; 001611 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; 001612 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; 001613 001614 /* Resolve names in table-valued-function arguments */ 001615 for(i=0; i<p->pSrc->nSrc; i++){ 001616 struct SrcList_item *pItem = &p->pSrc->a[i]; 001617 if( pItem->fg.isTabFunc 001618 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) 001619 ){ 001620 return WRC_Abort; 001621 } 001622 } 001623 001624 /* The ORDER BY and GROUP BY clauses may not refer to terms in 001625 ** outer queries 001626 */ 001627 sNC.pNext = 0; 001628 sNC.ncFlags |= NC_AllowAgg|NC_AllowWin; 001629 001630 /* If this is a converted compound query, move the ORDER BY clause from 001631 ** the sub-query back to the parent query. At this point each term 001632 ** within the ORDER BY clause has been transformed to an integer value. 001633 ** These integers will be replaced by copies of the corresponding result 001634 ** set expressions by the call to resolveOrderGroupBy() below. */ 001635 if( p->selFlags & SF_Converted ){ 001636 Select *pSub = p->pSrc->a[0].pSelect; 001637 p->pOrderBy = pSub->pOrderBy; 001638 pSub->pOrderBy = 0; 001639 } 001640 001641 /* Process the ORDER BY clause for singleton SELECT statements. 001642 ** The ORDER BY clause for compounds SELECT statements is handled 001643 ** below, after all of the result-sets for all of the elements of 001644 ** the compound have been resolved. 001645 ** 001646 ** If there is an ORDER BY clause on a term of a compound-select other 001647 ** than the right-most term, then that is a syntax error. But the error 001648 ** is not detected until much later, and so we need to go ahead and 001649 ** resolve those symbols on the incorrect ORDER BY for consistency. 001650 */ 001651 if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */ 001652 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") 001653 ){ 001654 return WRC_Abort; 001655 } 001656 if( db->mallocFailed ){ 001657 return WRC_Abort; 001658 } 001659 sNC.ncFlags &= ~NC_AllowWin; 001660 001661 /* Resolve the GROUP BY clause. At the same time, make sure 001662 ** the GROUP BY clause does not contain aggregate functions. 001663 */ 001664 if( pGroupBy ){ 001665 struct ExprList_item *pItem; 001666 001667 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ 001668 return WRC_Abort; 001669 } 001670 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 001671 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 001672 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 001673 "the GROUP BY clause"); 001674 return WRC_Abort; 001675 } 001676 } 001677 } 001678 001679 #ifndef SQLITE_OMIT_WINDOWFUNC 001680 if( IN_RENAME_OBJECT ){ 001681 Window *pWin; 001682 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){ 001683 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy) 001684 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition) 001685 ){ 001686 return WRC_Abort; 001687 } 001688 } 001689 } 001690 #endif 001691 001692 /* If this is part of a compound SELECT, check that it has the right 001693 ** number of expressions in the select list. */ 001694 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){ 001695 sqlite3SelectWrongNumTermsError(pParse, p->pNext); 001696 return WRC_Abort; 001697 } 001698 001699 /* Advance to the next term of the compound 001700 */ 001701 p = p->pPrior; 001702 nCompound++; 001703 } 001704 001705 /* Resolve the ORDER BY on a compound SELECT after all terms of 001706 ** the compound have been resolved. 001707 */ 001708 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ 001709 return WRC_Abort; 001710 } 001711 001712 return WRC_Prune; 001713 } 001714 001715 /* 001716 ** This routine walks an expression tree and resolves references to 001717 ** table columns and result-set columns. At the same time, do error 001718 ** checking on function usage and set a flag if any aggregate functions 001719 ** are seen. 001720 ** 001721 ** To resolve table columns references we look for nodes (or subtrees) of the 001722 ** form X.Y.Z or Y.Z or just Z where 001723 ** 001724 ** X: The name of a database. Ex: "main" or "temp" or 001725 ** the symbolic name assigned to an ATTACH-ed database. 001726 ** 001727 ** Y: The name of a table in a FROM clause. Or in a trigger 001728 ** one of the special names "old" or "new". 001729 ** 001730 ** Z: The name of a column in table Y. 001731 ** 001732 ** The node at the root of the subtree is modified as follows: 001733 ** 001734 ** Expr.op Changed to TK_COLUMN 001735 ** Expr.pTab Points to the Table object for X.Y 001736 ** Expr.iColumn The column index in X.Y. -1 for the rowid. 001737 ** Expr.iTable The VDBE cursor number for X.Y 001738 ** 001739 ** 001740 ** To resolve result-set references, look for expression nodes of the 001741 ** form Z (with no X and Y prefix) where the Z matches the right-hand 001742 ** size of an AS clause in the result-set of a SELECT. The Z expression 001743 ** is replaced by a copy of the left-hand side of the result-set expression. 001744 ** Table-name and function resolution occurs on the substituted expression 001745 ** tree. For example, in: 001746 ** 001747 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; 001748 ** 001749 ** The "x" term of the order by is replaced by "a+b" to render: 001750 ** 001751 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; 001752 ** 001753 ** Function calls are checked to make sure that the function is 001754 ** defined and that the correct number of arguments are specified. 001755 ** If the function is an aggregate function, then the NC_HasAgg flag is 001756 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. 001757 ** If an expression contains aggregate functions then the EP_Agg 001758 ** property on the expression is set. 001759 ** 001760 ** An error message is left in pParse if anything is amiss. The number 001761 ** if errors is returned. 001762 */ 001763 int sqlite3ResolveExprNames( 001764 NameContext *pNC, /* Namespace to resolve expressions in. */ 001765 Expr *pExpr /* The expression to be analyzed. */ 001766 ){ 001767 int savedHasAgg; 001768 Walker w; 001769 001770 if( pExpr==0 ) return SQLITE_OK; 001771 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin); 001772 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin); 001773 w.pParse = pNC->pParse; 001774 w.xExprCallback = resolveExprStep; 001775 w.xSelectCallback = resolveSelectStep; 001776 w.xSelectCallback2 = 0; 001777 w.u.pNC = pNC; 001778 #if SQLITE_MAX_EXPR_DEPTH>0 001779 w.pParse->nHeight += pExpr->nHeight; 001780 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){ 001781 return SQLITE_ERROR; 001782 } 001783 #endif 001784 sqlite3WalkExpr(&w, pExpr); 001785 #if SQLITE_MAX_EXPR_DEPTH>0 001786 w.pParse->nHeight -= pExpr->nHeight; 001787 #endif 001788 assert( EP_Agg==NC_HasAgg ); 001789 assert( EP_Win==NC_HasWin ); 001790 testcase( pNC->ncFlags & NC_HasAgg ); 001791 testcase( pNC->ncFlags & NC_HasWin ); 001792 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) ); 001793 pNC->ncFlags |= savedHasAgg; 001794 return pNC->nErr>0 || w.pParse->nErr>0; 001795 } 001796 001797 /* 001798 ** Resolve all names for all expression in an expression list. This is 001799 ** just like sqlite3ResolveExprNames() except that it works for an expression 001800 ** list rather than a single expression. 001801 */ 001802 int sqlite3ResolveExprListNames( 001803 NameContext *pNC, /* Namespace to resolve expressions in. */ 001804 ExprList *pList /* The expression list to be analyzed. */ 001805 ){ 001806 int i; 001807 if( pList ){ 001808 for(i=0; i<pList->nExpr; i++){ 001809 if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort; 001810 } 001811 } 001812 return WRC_Continue; 001813 } 001814 001815 /* 001816 ** Resolve all names in all expressions of a SELECT and in all 001817 ** decendents of the SELECT, including compounds off of p->pPrior, 001818 ** subqueries in expressions, and subqueries used as FROM clause 001819 ** terms. 001820 ** 001821 ** See sqlite3ResolveExprNames() for a description of the kinds of 001822 ** transformations that occur. 001823 ** 001824 ** All SELECT statements should have been expanded using 001825 ** sqlite3SelectExpand() prior to invoking this routine. 001826 */ 001827 void sqlite3ResolveSelectNames( 001828 Parse *pParse, /* The parser context */ 001829 Select *p, /* The SELECT statement being coded. */ 001830 NameContext *pOuterNC /* Name context for parent SELECT statement */ 001831 ){ 001832 Walker w; 001833 001834 assert( p!=0 ); 001835 w.xExprCallback = resolveExprStep; 001836 w.xSelectCallback = resolveSelectStep; 001837 w.xSelectCallback2 = 0; 001838 w.pParse = pParse; 001839 w.u.pNC = pOuterNC; 001840 sqlite3WalkSelect(&w, p); 001841 } 001842 001843 /* 001844 ** Resolve names in expressions that can only reference a single table 001845 ** or which cannot reference any tables at all. Examples: 001846 ** 001847 ** "type" flag 001848 ** ------------ 001849 ** (1) CHECK constraints NC_IsCheck 001850 ** (2) WHERE clauses on partial indices NC_PartIdx 001851 ** (3) Expressions in indexes on expressions NC_IdxExpr 001852 ** (4) Expression arguments to VACUUM INTO. 0 001853 ** (5) GENERATED ALWAYS as expressions NC_GenCol 001854 ** 001855 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN 001856 ** nodes of the expression is set to -1 and the Expr.iColumn value is 001857 ** set to the column number. In case (4), TK_COLUMN nodes cause an error. 001858 ** 001859 ** Any errors cause an error message to be set in pParse. 001860 */ 001861 int sqlite3ResolveSelfReference( 001862 Parse *pParse, /* Parsing context */ 001863 Table *pTab, /* The table being referenced, or NULL */ 001864 int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */ 001865 Expr *pExpr, /* Expression to resolve. May be NULL. */ 001866 ExprList *pList /* Expression list to resolve. May be NULL. */ 001867 ){ 001868 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ 001869 NameContext sNC; /* Name context for pParse->pNewTable */ 001870 int rc; 001871 001872 assert( type==0 || pTab!=0 ); 001873 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr 001874 || type==NC_GenCol || pTab==0 ); 001875 memset(&sNC, 0, sizeof(sNC)); 001876 memset(&sSrc, 0, sizeof(sSrc)); 001877 if( pTab ){ 001878 sSrc.nSrc = 1; 001879 sSrc.a[0].zName = pTab->zName; 001880 sSrc.a[0].pTab = pTab; 001881 sSrc.a[0].iCursor = -1; 001882 } 001883 sNC.pParse = pParse; 001884 sNC.pSrcList = &sSrc; 001885 sNC.ncFlags = type | NC_IsDDL; 001886 if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc; 001887 if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList); 001888 return rc; 001889 }