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 ** Magic table number to mean the EXCLUDED table in an UPSERT statement. 000021 */ 000022 #define EXCLUDED_TABLE_NUMBER 2 000023 000024 /* 000025 ** Walk the expression tree pExpr and increase the aggregate function 000026 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node. 000027 ** This needs to occur when copying a TK_AGG_FUNCTION node from an 000028 ** outer query into an inner subquery. 000029 ** 000030 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..) 000031 ** is a helper function - a callback for the tree walker. 000032 ** 000033 ** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c 000034 */ 000035 static int incrAggDepth(Walker *pWalker, Expr *pExpr){ 000036 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n; 000037 return WRC_Continue; 000038 } 000039 static void incrAggFunctionDepth(Expr *pExpr, int N){ 000040 if( N>0 ){ 000041 Walker w; 000042 memset(&w, 0, sizeof(w)); 000043 w.xExprCallback = incrAggDepth; 000044 w.u.n = N; 000045 sqlite3WalkExpr(&w, pExpr); 000046 } 000047 } 000048 000049 /* 000050 ** Turn the pExpr expression into an alias for the iCol-th column of the 000051 ** result set in pEList. 000052 ** 000053 ** If the reference is followed by a COLLATE operator, then make sure 000054 ** the COLLATE operator is preserved. For example: 000055 ** 000056 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase; 000057 ** 000058 ** Should be transformed into: 000059 ** 000060 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase; 000061 ** 000062 ** The nSubquery parameter specifies how many levels of subquery the 000063 ** alias is removed from the original expression. The usual value is 000064 ** zero but it might be more if the alias is contained within a subquery 000065 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION 000066 ** structures must be increased by the nSubquery amount. 000067 */ 000068 static void resolveAlias( 000069 Parse *pParse, /* Parsing context */ 000070 ExprList *pEList, /* A result set */ 000071 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */ 000072 Expr *pExpr, /* Transform this into an alias to the result set */ 000073 int nSubquery /* Number of subqueries that the label is moving */ 000074 ){ 000075 Expr *pOrig; /* The iCol-th column of the result set */ 000076 Expr *pDup; /* Copy of pOrig */ 000077 sqlite3 *db; /* The database connection */ 000078 000079 assert( iCol>=0 && iCol<pEList->nExpr ); 000080 pOrig = pEList->a[iCol].pExpr; 000081 assert( pOrig!=0 ); 000082 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) ); 000083 if( pExpr->pAggInfo ) return; 000084 db = pParse->db; 000085 pDup = sqlite3ExprDup(db, pOrig, 0); 000086 if( db->mallocFailed ){ 000087 sqlite3ExprDelete(db, pDup); 000088 pDup = 0; 000089 }else{ 000090 Expr temp; 000091 incrAggFunctionDepth(pDup, nSubquery); 000092 if( pExpr->op==TK_COLLATE ){ 000093 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 000094 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken); 000095 } 000096 memcpy(&temp, pDup, sizeof(Expr)); 000097 memcpy(pDup, pExpr, sizeof(Expr)); 000098 memcpy(pExpr, &temp, sizeof(Expr)); 000099 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 000100 if( ALWAYS(pExpr->y.pWin!=0) ){ 000101 pExpr->y.pWin->pOwner = pExpr; 000102 } 000103 } 000104 sqlite3ExprDeferredDelete(pParse, pDup); 000105 } 000106 } 000107 000108 /* 000109 ** Subqueries store the original database, table and column names for their 000110 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN", 000111 ** and mark the expression-list item by setting ExprList.a[].fg.eEName 000112 ** to ENAME_TAB. 000113 ** 000114 ** Check to see if the zSpan/eEName of the expression-list item passed to this 000115 ** routine matches the zDb, zTab, and zCol. If any of zDb, zTab, and zCol are 000116 ** NULL then those fields will match anything. Return true if there is a match, 000117 ** or false otherwise. 000118 ** 000119 ** SF_NestedFrom subqueries also store an entry for the implicit rowid (or 000120 ** _rowid_, or oid) column by setting ExprList.a[].fg.eEName to ENAME_ROWID, 000121 ** and setting zSpan to "DATABASE.TABLE.<rowid-alias>". This type of pItem 000122 ** argument matches if zCol is a rowid alias. If it is not NULL, (*pbRowid) 000123 ** is set to 1 if there is this kind of match. 000124 */ 000125 int sqlite3MatchEName( 000126 const struct ExprList_item *pItem, 000127 const char *zCol, 000128 const char *zTab, 000129 const char *zDb, 000130 int *pbRowid 000131 ){ 000132 int n; 000133 const char *zSpan; 000134 int eEName = pItem->fg.eEName; 000135 if( eEName!=ENAME_TAB && (eEName!=ENAME_ROWID || NEVER(pbRowid==0)) ){ 000136 return 0; 000137 } 000138 assert( pbRowid==0 || *pbRowid==0 ); 000139 zSpan = pItem->zEName; 000140 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} 000141 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){ 000142 return 0; 000143 } 000144 zSpan += n+1; 000145 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){} 000146 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){ 000147 return 0; 000148 } 000149 zSpan += n+1; 000150 if( zCol ){ 000151 if( eEName==ENAME_TAB && sqlite3StrICmp(zSpan, zCol)!=0 ) return 0; 000152 if( eEName==ENAME_ROWID && sqlite3IsRowid(zCol)==0 ) return 0; 000153 } 000154 if( eEName==ENAME_ROWID ) *pbRowid = 1; 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 ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN. 000177 ** return the appropriate colUsed mask. 000178 */ 000179 Bitmask sqlite3ExprColUsed(Expr *pExpr){ 000180 int n; 000181 Table *pExTab; 000182 000183 n = pExpr->iColumn; 000184 assert( ExprUseYTab(pExpr) ); 000185 pExTab = pExpr->y.pTab; 000186 assert( pExTab!=0 ); 000187 assert( n < pExTab->nCol ); 000188 if( (pExTab->tabFlags & TF_HasGenerated)!=0 000189 && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0 000190 ){ 000191 testcase( pExTab->nCol==BMS-1 ); 000192 testcase( pExTab->nCol==BMS ); 000193 return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1; 000194 }else{ 000195 testcase( n==BMS-1 ); 000196 testcase( n==BMS ); 000197 if( n>=BMS ) n = BMS-1; 000198 return ((Bitmask)1)<<n; 000199 } 000200 } 000201 000202 /* 000203 ** Create a new expression term for the column specified by pMatch and 000204 ** iColumn. Append this new expression term to the FULL JOIN Match set 000205 ** in *ppList. Create a new *ppList if this is the first term in the 000206 ** set. 000207 */ 000208 static void extendFJMatch( 000209 Parse *pParse, /* Parsing context */ 000210 ExprList **ppList, /* ExprList to extend */ 000211 SrcItem *pMatch, /* Source table containing the column */ 000212 i16 iColumn /* The column number */ 000213 ){ 000214 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); 000215 if( pNew ){ 000216 pNew->iTable = pMatch->iCursor; 000217 pNew->iColumn = iColumn; 000218 pNew->y.pTab = pMatch->pTab; 000219 assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ); 000220 ExprSetProperty(pNew, EP_CanBeNull); 000221 *ppList = sqlite3ExprListAppend(pParse, *ppList, pNew); 000222 } 000223 } 000224 000225 /* 000226 ** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab. 000227 */ 000228 static SQLITE_NOINLINE int isValidSchemaTableName( 000229 const char *zTab, /* Name as it appears in the SQL */ 000230 Table *pTab, /* The schema table we are trying to match */ 000231 const char *zDb /* non-NULL if a database qualifier is present */ 000232 ){ 000233 const char *zLegacy; 000234 assert( pTab!=0 ); 000235 assert( pTab->tnum==1 ); 000236 if( sqlite3StrNICmp(zTab, "sqlite_", 7)!=0 ) return 0; 000237 zLegacy = pTab->zName; 000238 if( strcmp(zLegacy+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){ 000239 if( sqlite3StrICmp(zTab+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){ 000240 return 1; 000241 } 000242 if( zDb==0 ) return 0; 000243 if( sqlite3StrICmp(zTab+7, &LEGACY_SCHEMA_TABLE[7])==0 ) return 1; 000244 if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1; 000245 }else{ 000246 if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1; 000247 } 000248 return 0; 000249 } 000250 000251 /* 000252 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up 000253 ** that name in the set of source tables in pSrcList and make the pExpr 000254 ** expression node refer back to that source column. The following changes 000255 ** are made to pExpr: 000256 ** 000257 ** pExpr->iDb Set the index in db->aDb[] of the database X 000258 ** (even if X is implied). 000259 ** pExpr->iTable Set to the cursor number for the table obtained 000260 ** from pSrcList. 000261 ** pExpr->y.pTab Points to the Table structure of X.Y (even if 000262 ** X and/or Y are implied.) 000263 ** pExpr->iColumn Set to the column number within the table. 000264 ** pExpr->op Set to TK_COLUMN. 000265 ** pExpr->pLeft Any expression this points to is deleted 000266 ** pExpr->pRight Any expression this points to is deleted. 000267 ** 000268 ** The zDb variable is the name of the database (the "X"). This value may be 000269 ** NULL meaning that name is of the form Y.Z or Z. Any available database 000270 ** can be used. The zTable variable is the name of the table (the "Y"). This 000271 ** value can be NULL if zDb is also NULL. If zTable is NULL it 000272 ** means that the form of the name is Z and that columns from any table 000273 ** can be used. 000274 ** 000275 ** If the name cannot be resolved unambiguously, leave an error message 000276 ** in pParse and return WRC_Abort. Return WRC_Prune on success. 000277 */ 000278 static int lookupName( 000279 Parse *pParse, /* The parsing context */ 000280 const char *zDb, /* Name of the database containing table, or NULL */ 000281 const char *zTab, /* Name of table containing column, or NULL */ 000282 const Expr *pRight, /* Name of the column. */ 000283 NameContext *pNC, /* The name context used to resolve the name */ 000284 Expr *pExpr /* Make this EXPR node point to the selected column */ 000285 ){ 000286 int i, j; /* Loop counters */ 000287 int cnt = 0; /* Number of matching column names */ 000288 int cntTab = 0; /* Number of potential "rowid" matches */ 000289 int nSubquery = 0; /* How many levels of subquery */ 000290 sqlite3 *db = pParse->db; /* The database connection */ 000291 SrcItem *pItem; /* Use for looping over pSrcList items */ 000292 SrcItem *pMatch = 0; /* The matching pSrcList item */ 000293 NameContext *pTopNC = pNC; /* First namecontext in the list */ 000294 Schema *pSchema = 0; /* Schema of the expression */ 000295 int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ 000296 Table *pTab = 0; /* Table holding the row */ 000297 Column *pCol; /* A column of pTab */ 000298 ExprList *pFJMatch = 0; /* Matches for FULL JOIN .. USING */ 000299 const char *zCol = pRight->u.zToken; 000300 000301 assert( pNC ); /* the name context cannot be NULL. */ 000302 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ 000303 assert( zDb==0 || zTab!=0 ); 000304 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 000305 000306 /* Initialize the node to no-match */ 000307 pExpr->iTable = -1; 000308 ExprSetVVAProperty(pExpr, EP_NoReduce); 000309 000310 /* Translate the schema name in zDb into a pointer to the corresponding 000311 ** schema. If not found, pSchema will remain NULL and nothing will match 000312 ** resulting in an appropriate error message toward the end of this routine 000313 */ 000314 if( zDb ){ 000315 testcase( pNC->ncFlags & NC_PartIdx ); 000316 testcase( pNC->ncFlags & NC_IsCheck ); 000317 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ 000318 /* Silently ignore database qualifiers inside CHECK constraints and 000319 ** partial indices. Do not raise errors because that might break 000320 ** legacy and because it does not hurt anything to just ignore the 000321 ** database name. */ 000322 zDb = 0; 000323 }else{ 000324 for(i=0; i<db->nDb; i++){ 000325 assert( db->aDb[i].zDbSName ); 000326 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ 000327 pSchema = db->aDb[i].pSchema; 000328 break; 000329 } 000330 } 000331 if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){ 000332 /* This branch is taken when the main database has been renamed 000333 ** using SQLITE_DBCONFIG_MAINDBNAME. */ 000334 pSchema = db->aDb[0].pSchema; 000335 zDb = db->aDb[0].zDbSName; 000336 } 000337 } 000338 } 000339 000340 /* Start at the inner-most context and move outward until a match is found */ 000341 assert( pNC && cnt==0 ); 000342 do{ 000343 ExprList *pEList; 000344 SrcList *pSrcList = pNC->pSrcList; 000345 000346 if( pSrcList ){ 000347 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ 000348 u8 hCol; 000349 pTab = pItem->pTab; 000350 assert( pTab!=0 && pTab->zName!=0 ); 000351 assert( pTab->nCol>0 || pParse->nErr ); 000352 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) ); 000353 if( pItem->fg.isNestedFrom ){ 000354 /* In this case, pItem is a subquery that has been formed from a 000355 ** parenthesized subset of the FROM clause terms. Example: 000356 ** .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ... 000357 ** \_________________________/ 000358 ** This pItem -------------^ 000359 */ 000360 int hit = 0; 000361 assert( pItem->pSelect!=0 ); 000362 pEList = pItem->pSelect->pEList; 000363 assert( pEList!=0 ); 000364 assert( pEList->nExpr==pTab->nCol ); 000365 for(j=0; j<pEList->nExpr; j++){ 000366 int bRowid = 0; /* True if possible rowid match */ 000367 if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb, &bRowid) ){ 000368 continue; 000369 } 000370 if( bRowid==0 ){ 000371 if( cnt>0 ){ 000372 if( pItem->fg.isUsing==0 000373 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0 000374 ){ 000375 /* Two or more tables have the same column name which is 000376 ** not joined by USING. This is an error. Signal as much 000377 ** by clearing pFJMatch and letting cnt go above 1. */ 000378 sqlite3ExprListDelete(db, pFJMatch); 000379 pFJMatch = 0; 000380 }else 000381 if( (pItem->fg.jointype & JT_RIGHT)==0 ){ 000382 /* An INNER or LEFT JOIN. Use the left-most table */ 000383 continue; 000384 }else 000385 if( (pItem->fg.jointype & JT_LEFT)==0 ){ 000386 /* A RIGHT JOIN. Use the right-most table */ 000387 cnt = 0; 000388 sqlite3ExprListDelete(db, pFJMatch); 000389 pFJMatch = 0; 000390 }else{ 000391 /* For a FULL JOIN, we must construct a coalesce() func */ 000392 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn); 000393 } 000394 } 000395 cnt++; 000396 hit = 1; 000397 }else if( cnt>0 ){ 000398 /* This is a potential rowid match, but there has already been 000399 ** a real match found. So this can be ignored. */ 000400 continue; 000401 } 000402 cntTab++; 000403 pMatch = pItem; 000404 pExpr->iColumn = j; 000405 pEList->a[j].fg.bUsed = 1; 000406 000407 /* rowid cannot be part of a USING clause - assert() this. */ 000408 assert( bRowid==0 || pEList->a[j].fg.bUsingTerm==0 ); 000409 if( pEList->a[j].fg.bUsingTerm ) break; 000410 } 000411 if( hit || zTab==0 ) continue; 000412 } 000413 assert( zDb==0 || zTab!=0 ); 000414 if( zTab ){ 000415 if( zDb ){ 000416 if( pTab->pSchema!=pSchema ) continue; 000417 if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue; 000418 } 000419 if( pItem->zAlias!=0 ){ 000420 if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){ 000421 continue; 000422 } 000423 }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){ 000424 if( pTab->tnum!=1 ) continue; 000425 if( !isValidSchemaTableName(zTab, pTab, zDb) ) continue; 000426 } 000427 assert( ExprUseYTab(pExpr) ); 000428 if( IN_RENAME_OBJECT && pItem->zAlias ){ 000429 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); 000430 } 000431 } 000432 hCol = sqlite3StrIHash(zCol); 000433 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ 000434 if( pCol->hName==hCol 000435 && sqlite3StrICmp(pCol->zCnName, zCol)==0 000436 ){ 000437 if( cnt>0 ){ 000438 if( pItem->fg.isUsing==0 000439 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0 000440 ){ 000441 /* Two or more tables have the same column name which is 000442 ** not joined by USING. This is an error. Signal as much 000443 ** by clearing pFJMatch and letting cnt go above 1. */ 000444 sqlite3ExprListDelete(db, pFJMatch); 000445 pFJMatch = 0; 000446 }else 000447 if( (pItem->fg.jointype & JT_RIGHT)==0 ){ 000448 /* An INNER or LEFT JOIN. Use the left-most table */ 000449 continue; 000450 }else 000451 if( (pItem->fg.jointype & JT_LEFT)==0 ){ 000452 /* A RIGHT JOIN. Use the right-most table */ 000453 cnt = 0; 000454 sqlite3ExprListDelete(db, pFJMatch); 000455 pFJMatch = 0; 000456 }else{ 000457 /* For a FULL JOIN, we must construct a coalesce() func */ 000458 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn); 000459 } 000460 } 000461 cnt++; 000462 pMatch = pItem; 000463 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ 000464 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; 000465 if( pItem->fg.isNestedFrom ){ 000466 sqlite3SrcItemColumnUsed(pItem, j); 000467 } 000468 break; 000469 } 000470 } 000471 if( 0==cnt && VisibleRowid(pTab) ){ 000472 /* pTab is a potential ROWID match. Keep track of it and match 000473 ** the ROWID later if that seems appropriate. (Search for "cntTab" 000474 ** to find related code.) Only allow a ROWID match if there is 000475 ** a single ROWID match candidate. 000476 */ 000477 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW 000478 /* In SQLITE_ALLOW_ROWID_IN_VIEW mode, allow a ROWID match 000479 ** if there is a single VIEW candidate or if there is a single 000480 ** non-VIEW candidate plus multiple VIEW candidates. In other 000481 ** words non-VIEW candidate terms take precedence over VIEWs. 000482 */ 000483 if( cntTab==0 000484 || (cntTab==1 000485 && ALWAYS(pMatch!=0) 000486 && ALWAYS(pMatch->pTab!=0) 000487 && (pMatch->pTab->tabFlags & TF_Ephemeral)!=0 000488 && (pTab->tabFlags & TF_Ephemeral)==0) 000489 ){ 000490 cntTab = 1; 000491 pMatch = pItem; 000492 }else{ 000493 cntTab++; 000494 } 000495 #else 000496 /* The (much more common) non-SQLITE_ALLOW_ROWID_IN_VIEW case is 000497 ** simpler since we require exactly one candidate, which will 000498 ** always be a non-VIEW 000499 */ 000500 cntTab++; 000501 pMatch = pItem; 000502 #endif 000503 } 000504 } 000505 if( pMatch ){ 000506 pExpr->iTable = pMatch->iCursor; 000507 assert( ExprUseYTab(pExpr) ); 000508 pExpr->y.pTab = pMatch->pTab; 000509 if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){ 000510 ExprSetProperty(pExpr, EP_CanBeNull); 000511 } 000512 pSchema = pExpr->y.pTab->pSchema; 000513 } 000514 } /* if( pSrcList ) */ 000515 000516 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) 000517 /* If we have not already resolved the name, then maybe 000518 ** it is a new.* or old.* trigger argument reference. Or 000519 ** maybe it is an excluded.* from an upsert. Or maybe it is 000520 ** a reference in the RETURNING clause to a table being modified. 000521 */ 000522 if( cnt==0 && zDb==0 ){ 000523 pTab = 0; 000524 #ifndef SQLITE_OMIT_TRIGGER 000525 if( pParse->pTriggerTab!=0 ){ 000526 int op = pParse->eTriggerOp; 000527 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); 000528 if( pParse->bReturning ){ 000529 if( (pNC->ncFlags & NC_UBaseReg)!=0 000530 && ALWAYS(zTab==0 000531 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0 000532 || isValidSchemaTableName(zTab, pParse->pTriggerTab, 0)) 000533 ){ 000534 pExpr->iTable = op!=TK_DELETE; 000535 pTab = pParse->pTriggerTab; 000536 } 000537 }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){ 000538 pExpr->iTable = 1; 000539 pTab = pParse->pTriggerTab; 000540 }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){ 000541 pExpr->iTable = 0; 000542 pTab = pParse->pTriggerTab; 000543 } 000544 } 000545 #endif /* SQLITE_OMIT_TRIGGER */ 000546 #ifndef SQLITE_OMIT_UPSERT 000547 if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){ 000548 Upsert *pUpsert = pNC->uNC.pUpsert; 000549 if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){ 000550 pTab = pUpsert->pUpsertSrc->a[0].pTab; 000551 pExpr->iTable = EXCLUDED_TABLE_NUMBER; 000552 } 000553 } 000554 #endif /* SQLITE_OMIT_UPSERT */ 000555 000556 if( pTab ){ 000557 int iCol; 000558 u8 hCol = sqlite3StrIHash(zCol); 000559 pSchema = pTab->pSchema; 000560 cntTab++; 000561 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ 000562 if( pCol->hName==hCol 000563 && sqlite3StrICmp(pCol->zCnName, zCol)==0 000564 ){ 000565 if( iCol==pTab->iPKey ){ 000566 iCol = -1; 000567 } 000568 break; 000569 } 000570 } 000571 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ 000572 /* IMP: R-51414-32910 */ 000573 iCol = -1; 000574 } 000575 if( iCol<pTab->nCol ){ 000576 cnt++; 000577 pMatch = 0; 000578 #ifndef SQLITE_OMIT_UPSERT 000579 if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){ 000580 testcase( iCol==(-1) ); 000581 assert( ExprUseYTab(pExpr) ); 000582 if( IN_RENAME_OBJECT ){ 000583 pExpr->iColumn = iCol; 000584 pExpr->y.pTab = pTab; 000585 eNewExprOp = TK_COLUMN; 000586 }else{ 000587 pExpr->iTable = pNC->uNC.pUpsert->regData + 000588 sqlite3TableColumnToStorage(pTab, iCol); 000589 eNewExprOp = TK_REGISTER; 000590 } 000591 }else 000592 #endif /* SQLITE_OMIT_UPSERT */ 000593 { 000594 assert( ExprUseYTab(pExpr) ); 000595 pExpr->y.pTab = pTab; 000596 if( pParse->bReturning ){ 000597 eNewExprOp = TK_REGISTER; 000598 pExpr->op2 = TK_COLUMN; 000599 pExpr->iColumn = iCol; 000600 pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable + 000601 sqlite3TableColumnToStorage(pTab, iCol) + 1; 000602 }else{ 000603 pExpr->iColumn = (i16)iCol; 000604 eNewExprOp = TK_TRIGGER; 000605 #ifndef SQLITE_OMIT_TRIGGER 000606 if( iCol<0 ){ 000607 pExpr->affExpr = SQLITE_AFF_INTEGER; 000608 }else if( pExpr->iTable==0 ){ 000609 testcase( iCol==31 ); 000610 testcase( iCol==32 ); 000611 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); 000612 }else{ 000613 testcase( iCol==31 ); 000614 testcase( iCol==32 ); 000615 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); 000616 } 000617 #endif /* SQLITE_OMIT_TRIGGER */ 000618 } 000619 } 000620 } 000621 } 000622 } 000623 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ 000624 000625 /* 000626 ** Perhaps the name is a reference to the ROWID 000627 */ 000628 if( cnt==0 000629 && cntTab>=1 000630 && pMatch 000631 && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0 000632 && sqlite3IsRowid(zCol) 000633 && ALWAYS(VisibleRowid(pMatch->pTab) || pMatch->fg.isNestedFrom) 000634 ){ 000635 cnt = cntTab; 000636 #if SQLITE_ALLOW_ROWID_IN_VIEW+0==2 000637 if( pMatch->pTab!=0 && IsView(pMatch->pTab) ){ 000638 eNewExprOp = TK_NULL; 000639 } 000640 #endif 000641 if( pMatch->fg.isNestedFrom==0 ) pExpr->iColumn = -1; 000642 pExpr->affExpr = SQLITE_AFF_INTEGER; 000643 } 000644 000645 /* 000646 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z 000647 ** might refer to an result-set alias. This happens, for example, when 000648 ** we are resolving names in the WHERE clause of the following command: 000649 ** 000650 ** SELECT a+b AS x FROM table WHERE x<10; 000651 ** 000652 ** In cases like this, replace pExpr with a copy of the expression that 000653 ** forms the result set entry ("a+b" in the example) and return immediately. 000654 ** Note that the expression in the result set should have already been 000655 ** resolved by the time the WHERE clause is resolved. 000656 ** 000657 ** The ability to use an output result-set column in the WHERE, GROUP BY, 000658 ** or HAVING clauses, or as part of a larger expression in the ORDER BY 000659 ** clause is not standard SQL. This is a (goofy) SQLite extension, that 000660 ** is supported for backwards compatibility only. Hence, we issue a warning 000661 ** on sqlite3_log() whenever the capability is used. 000662 */ 000663 if( cnt==0 000664 && (pNC->ncFlags & NC_UEList)!=0 000665 && zTab==0 000666 ){ 000667 pEList = pNC->uNC.pEList; 000668 assert( pEList!=0 ); 000669 for(j=0; j<pEList->nExpr; j++){ 000670 char *zAs = pEList->a[j].zEName; 000671 if( pEList->a[j].fg.eEName==ENAME_NAME 000672 && sqlite3_stricmp(zAs, zCol)==0 000673 ){ 000674 Expr *pOrig; 000675 assert( pExpr->pLeft==0 && pExpr->pRight==0 ); 000676 assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 ); 000677 assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 ); 000678 pOrig = pEList->a[j].pExpr; 000679 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ 000680 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); 000681 return WRC_Abort; 000682 } 000683 if( ExprHasProperty(pOrig, EP_Win) 000684 && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC ) 000685 ){ 000686 sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs); 000687 return WRC_Abort; 000688 } 000689 if( sqlite3ExprVectorSize(pOrig)!=1 ){ 000690 sqlite3ErrorMsg(pParse, "row value misused"); 000691 return WRC_Abort; 000692 } 000693 resolveAlias(pParse, pEList, j, pExpr, nSubquery); 000694 cnt = 1; 000695 pMatch = 0; 000696 assert( zTab==0 && zDb==0 ); 000697 if( IN_RENAME_OBJECT ){ 000698 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); 000699 } 000700 goto lookupname_end; 000701 } 000702 } 000703 } 000704 000705 /* Advance to the next name context. The loop will exit when either 000706 ** we have a match (cnt>0) or when we run out of name contexts. 000707 */ 000708 if( cnt ) break; 000709 pNC = pNC->pNext; 000710 nSubquery++; 000711 }while( pNC ); 000712 000713 000714 /* 000715 ** If X and Y are NULL (in other words if only the column name Z is 000716 ** supplied) and the value of Z is enclosed in double-quotes, then 000717 ** Z is a string literal if it doesn't match any column names. In that 000718 ** case, we need to return right away and not make any changes to 000719 ** pExpr. 000720 ** 000721 ** Because no reference was made to outer contexts, the pNC->nRef 000722 ** fields are not changed in any context. 000723 */ 000724 if( cnt==0 && zTab==0 ){ 000725 assert( pExpr->op==TK_ID ); 000726 if( ExprHasProperty(pExpr,EP_DblQuoted) 000727 && areDoubleQuotedStringsEnabled(db, pTopNC) 000728 ){ 000729 /* If a double-quoted identifier does not match any known column name, 000730 ** then treat it as a string. 000731 ** 000732 ** This hack was added in the early days of SQLite in a misguided attempt 000733 ** to be compatible with MySQL 3.x, which used double-quotes for strings. 000734 ** I now sorely regret putting in this hack. The effect of this hack is 000735 ** that misspelled identifier names are silently converted into strings 000736 ** rather than causing an error, to the frustration of countless 000737 ** programmers. To all those frustrated programmers, my apologies. 000738 ** 000739 ** Someday, I hope to get rid of this hack. Unfortunately there is 000740 ** a huge amount of legacy SQL that uses it. So for now, we just 000741 ** issue a warning. 000742 */ 000743 sqlite3_log(SQLITE_WARNING, 000744 "double-quoted string literal: \"%w\"", zCol); 000745 #ifdef SQLITE_ENABLE_NORMALIZE 000746 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); 000747 #endif 000748 pExpr->op = TK_STRING; 000749 memset(&pExpr->y, 0, sizeof(pExpr->y)); 000750 return WRC_Prune; 000751 } 000752 if( sqlite3ExprIdToTrueFalse(pExpr) ){ 000753 return WRC_Prune; 000754 } 000755 } 000756 000757 /* 000758 ** cnt==0 means there was not match. 000759 ** cnt>1 means there were two or more matches. 000760 ** 000761 ** cnt==0 is always an error. cnt>1 is often an error, but might 000762 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING. 000763 */ 000764 assert( pFJMatch==0 || cnt>0 ); 000765 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) ); 000766 if( cnt!=1 ){ 000767 const char *zErr; 000768 if( pFJMatch ){ 000769 if( pFJMatch->nExpr==cnt-1 ){ 000770 if( ExprHasProperty(pExpr,EP_Leaf) ){ 000771 ExprClearProperty(pExpr,EP_Leaf); 000772 }else{ 000773 sqlite3ExprDelete(db, pExpr->pLeft); 000774 pExpr->pLeft = 0; 000775 sqlite3ExprDelete(db, pExpr->pRight); 000776 pExpr->pRight = 0; 000777 } 000778 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn); 000779 pExpr->op = TK_FUNCTION; 000780 pExpr->u.zToken = "coalesce"; 000781 pExpr->x.pList = pFJMatch; 000782 cnt = 1; 000783 goto lookupname_end; 000784 }else{ 000785 sqlite3ExprListDelete(db, pFJMatch); 000786 pFJMatch = 0; 000787 } 000788 } 000789 zErr = cnt==0 ? "no such column" : "ambiguous column name"; 000790 if( zDb ){ 000791 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); 000792 }else if( zTab ){ 000793 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); 000794 }else if( cnt==0 && ExprHasProperty(pRight,EP_DblQuoted) ){ 000795 sqlite3ErrorMsg(pParse, "%s: \"%s\" - should this be a" 000796 " string literal in single-quotes?", 000797 zErr, zCol); 000798 }else{ 000799 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); 000800 } 000801 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr); 000802 pParse->checkSchema = 1; 000803 pTopNC->nNcErr++; 000804 eNewExprOp = TK_NULL; 000805 } 000806 assert( pFJMatch==0 ); 000807 000808 /* Remove all substructure from pExpr */ 000809 if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){ 000810 sqlite3ExprDelete(db, pExpr->pLeft); 000811 pExpr->pLeft = 0; 000812 sqlite3ExprDelete(db, pExpr->pRight); 000813 pExpr->pRight = 0; 000814 ExprSetProperty(pExpr, EP_Leaf); 000815 } 000816 000817 /* If a column from a table in pSrcList is referenced, then record 000818 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes 000819 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is 000820 ** set if the 63rd or any subsequent column is used. 000821 ** 000822 ** The colUsed mask is an optimization used to help determine if an 000823 ** index is a covering index. The correct answer is still obtained 000824 ** if the mask contains extra set bits. However, it is important to 000825 ** avoid setting bits beyond the maximum column number of the table. 000826 ** (See ticket [b92e5e8ec2cdbaa1]). 000827 ** 000828 ** If a generated column is referenced, set bits for every column 000829 ** of the table. 000830 */ 000831 if( pMatch ){ 000832 if( pExpr->iColumn>=0 ){ 000833 pMatch->colUsed |= sqlite3ExprColUsed(pExpr); 000834 }else{ 000835 pMatch->fg.rowidUsed = 1; 000836 } 000837 } 000838 000839 pExpr->op = eNewExprOp; 000840 lookupname_end: 000841 if( cnt==1 ){ 000842 assert( pNC!=0 ); 000843 #ifndef SQLITE_OMIT_AUTHORIZATION 000844 if( pParse->db->xAuth 000845 && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER) 000846 ){ 000847 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); 000848 } 000849 #endif 000850 /* Increment the nRef value on all name contexts from TopNC up to 000851 ** the point where the name matched. */ 000852 for(;;){ 000853 assert( pTopNC!=0 ); 000854 pTopNC->nRef++; 000855 if( pTopNC==pNC ) break; 000856 pTopNC = pTopNC->pNext; 000857 } 000858 return WRC_Prune; 000859 } else { 000860 return WRC_Abort; 000861 } 000862 } 000863 000864 /* 000865 ** Allocate and return a pointer to an expression to load the column iCol 000866 ** from datasource iSrc in SrcList pSrc. 000867 */ 000868 Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){ 000869 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0); 000870 if( p ){ 000871 SrcItem *pItem = &pSrc->a[iSrc]; 000872 Table *pTab; 000873 assert( ExprUseYTab(p) ); 000874 pTab = p->y.pTab = pItem->pTab; 000875 p->iTable = pItem->iCursor; 000876 if( p->y.pTab->iPKey==iCol ){ 000877 p->iColumn = -1; 000878 }else{ 000879 p->iColumn = (ynVar)iCol; 000880 if( (pTab->tabFlags & TF_HasGenerated)!=0 000881 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0 000882 ){ 000883 testcase( pTab->nCol==63 ); 000884 testcase( pTab->nCol==64 ); 000885 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1; 000886 }else{ 000887 testcase( iCol==BMS ); 000888 testcase( iCol==BMS-1 ); 000889 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol); 000890 } 000891 } 000892 } 000893 return p; 000894 } 000895 000896 /* 000897 ** Report an error that an expression is not valid for some set of 000898 ** pNC->ncFlags values determined by validMask. 000899 ** 000900 ** static void notValid( 000901 ** Parse *pParse, // Leave error message here 000902 ** NameContext *pNC, // The name context 000903 ** const char *zMsg, // Type of error 000904 ** int validMask, // Set of contexts for which prohibited 000905 ** Expr *pExpr // Invalidate this expression on error 000906 ** ){...} 000907 ** 000908 ** As an optimization, since the conditional is almost always false 000909 ** (because errors are rare), the conditional is moved outside of the 000910 ** function call using a macro. 000911 */ 000912 static void notValidImpl( 000913 Parse *pParse, /* Leave error message here */ 000914 NameContext *pNC, /* The name context */ 000915 const char *zMsg, /* Type of error */ 000916 Expr *pExpr, /* Invalidate this expression on error */ 000917 Expr *pError /* Associate error with this expression */ 000918 ){ 000919 const char *zIn = "partial index WHERE clauses"; 000920 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions"; 000921 #ifndef SQLITE_OMIT_CHECK 000922 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints"; 000923 #endif 000924 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 000925 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns"; 000926 #endif 000927 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn); 000928 if( pExpr ) pExpr->op = TK_NULL; 000929 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError); 000930 } 000931 #define sqlite3ResolveNotValid(P,N,M,X,E,R) \ 000932 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \ 000933 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R); 000934 000935 /* 000936 ** Expression p should encode a floating point value between 1.0 and 0.0. 000937 ** Return 1024 times this value. Or return -1 if p is not a floating point 000938 ** value between 1.0 and 0.0. 000939 */ 000940 static int exprProbability(Expr *p){ 000941 double r = -1.0; 000942 if( p->op!=TK_FLOAT ) return -1; 000943 assert( !ExprHasProperty(p, EP_IntValue) ); 000944 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8); 000945 assert( r>=0.0 ); 000946 if( r>1.0 ) return -1; 000947 return (int)(r*134217728.0); 000948 } 000949 000950 /* 000951 ** This routine is callback for sqlite3WalkExpr(). 000952 ** 000953 ** Resolve symbolic names into TK_COLUMN operators for the current 000954 ** node in the expression tree. Return 0 to continue the search down 000955 ** the tree or 2 to abort the tree walk. 000956 ** 000957 ** This routine also does error checking and name resolution for 000958 ** function names. The operator for aggregate functions is changed 000959 ** to TK_AGG_FUNCTION. 000960 */ 000961 static int resolveExprStep(Walker *pWalker, Expr *pExpr){ 000962 NameContext *pNC; 000963 Parse *pParse; 000964 000965 pNC = pWalker->u.pNC; 000966 assert( pNC!=0 ); 000967 pParse = pNC->pParse; 000968 assert( pParse==pWalker->pParse ); 000969 000970 #ifndef NDEBUG 000971 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){ 000972 SrcList *pSrcList = pNC->pSrcList; 000973 int i; 000974 for(i=0; i<pNC->pSrcList->nSrc; i++){ 000975 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab); 000976 } 000977 } 000978 #endif 000979 switch( pExpr->op ){ 000980 000981 /* The special operator TK_ROW means use the rowid for the first 000982 ** column in the FROM clause. This is used by the LIMIT and ORDER BY 000983 ** clause processing on UPDATE and DELETE statements, and by 000984 ** UPDATE ... FROM statement processing. 000985 */ 000986 case TK_ROW: { 000987 SrcList *pSrcList = pNC->pSrcList; 000988 SrcItem *pItem; 000989 assert( pSrcList && pSrcList->nSrc>=1 ); 000990 pItem = pSrcList->a; 000991 pExpr->op = TK_COLUMN; 000992 assert( ExprUseYTab(pExpr) ); 000993 pExpr->y.pTab = pItem->pTab; 000994 pExpr->iTable = pItem->iCursor; 000995 pExpr->iColumn--; 000996 pExpr->affExpr = SQLITE_AFF_INTEGER; 000997 break; 000998 } 000999 001000 /* An optimization: Attempt to convert 001001 ** 001002 ** "expr IS NOT NULL" --> "TRUE" 001003 ** "expr IS NULL" --> "FALSE" 001004 ** 001005 ** if we can prove that "expr" is never NULL. Call this the 001006 ** "NOT NULL strength reduction optimization". 001007 ** 001008 ** If this optimization occurs, also restore the NameContext ref-counts 001009 ** to the state they where in before the "column" LHS expression was 001010 ** resolved. This prevents "column" from being counted as having been 001011 ** referenced, which might prevent a SELECT from being erroneously 001012 ** marked as correlated. 001013 ** 001014 ** 2024-03-28: Beware of aggregates. A bare column of aggregated table 001015 ** can still evaluate to NULL even though it is marked as NOT NULL. 001016 ** Example: 001017 ** 001018 ** CREATE TABLE t1(a INT NOT NULL); 001019 ** SELECT a, a IS NULL, a IS NOT NULL, count(*) FROM t1; 001020 ** 001021 ** The "a IS NULL" and "a IS NOT NULL" expressions cannot be optimized 001022 ** here because at the time this case is hit, we do not yet know whether 001023 ** or not t1 is being aggregated. We have to assume the worst and omit 001024 ** the optimization. The only time it is safe to apply this optimization 001025 ** is within the WHERE clause. 001026 */ 001027 case TK_NOTNULL: 001028 case TK_ISNULL: { 001029 int anRef[8]; 001030 NameContext *p; 001031 int i; 001032 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){ 001033 anRef[i] = p->nRef; 001034 } 001035 sqlite3WalkExpr(pWalker, pExpr->pLeft); 001036 if( IN_RENAME_OBJECT ) return WRC_Prune; 001037 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){ 001038 /* The expression can be NULL. So the optimization does not apply */ 001039 return WRC_Prune; 001040 } 001041 001042 for(i=0, p=pNC; p; p=p->pNext, i++){ 001043 if( (p->ncFlags & NC_Where)==0 ){ 001044 return WRC_Prune; /* Not in a WHERE clause. Unsafe to optimize. */ 001045 } 001046 } 001047 testcase( ExprHasProperty(pExpr, EP_OuterON) ); 001048 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 001049 #if TREETRACE_ENABLED 001050 if( sqlite3TreeTrace & 0x80000 ){ 001051 sqlite3DebugPrintf( 001052 "NOT NULL strength reduction converts the following to %d:\n", 001053 pExpr->op==TK_NOTNULL 001054 ); 001055 sqlite3ShowExpr(pExpr); 001056 } 001057 #endif /* TREETRACE_ENABLED */ 001058 pExpr->u.iValue = (pExpr->op==TK_NOTNULL); 001059 pExpr->flags |= EP_IntValue; 001060 pExpr->op = TK_INTEGER; 001061 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){ 001062 p->nRef = anRef[i]; 001063 } 001064 sqlite3ExprDelete(pParse->db, pExpr->pLeft); 001065 pExpr->pLeft = 0; 001066 return WRC_Prune; 001067 } 001068 001069 /* A column name: ID 001070 ** Or table name and column name: ID.ID 001071 ** Or a database, table and column: ID.ID.ID 001072 ** 001073 ** The TK_ID and TK_OUT cases are combined so that there will only 001074 ** be one call to lookupName(). Then the compiler will in-line 001075 ** lookupName() for a size reduction and performance increase. 001076 */ 001077 case TK_ID: 001078 case TK_DOT: { 001079 const char *zTable; 001080 const char *zDb; 001081 Expr *pRight; 001082 001083 if( pExpr->op==TK_ID ){ 001084 zDb = 0; 001085 zTable = 0; 001086 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 001087 pRight = pExpr; 001088 }else{ 001089 Expr *pLeft = pExpr->pLeft; 001090 testcase( pNC->ncFlags & NC_IdxExpr ); 001091 testcase( pNC->ncFlags & NC_GenCol ); 001092 sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator", 001093 NC_IdxExpr|NC_GenCol, 0, pExpr); 001094 pRight = pExpr->pRight; 001095 if( pRight->op==TK_ID ){ 001096 zDb = 0; 001097 }else{ 001098 assert( pRight->op==TK_DOT ); 001099 assert( !ExprHasProperty(pRight, EP_IntValue) ); 001100 zDb = pLeft->u.zToken; 001101 pLeft = pRight->pLeft; 001102 pRight = pRight->pRight; 001103 } 001104 assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) ); 001105 zTable = pLeft->u.zToken; 001106 assert( ExprUseYTab(pExpr) ); 001107 if( IN_RENAME_OBJECT ){ 001108 sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight); 001109 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft); 001110 } 001111 } 001112 return lookupName(pParse, zDb, zTable, pRight, pNC, pExpr); 001113 } 001114 001115 /* Resolve function names 001116 */ 001117 case TK_FUNCTION: { 001118 ExprList *pList = pExpr->x.pList; /* The argument list */ 001119 int n = pList ? pList->nExpr : 0; /* Number of arguments */ 001120 int no_such_func = 0; /* True if no such function exists */ 001121 int wrong_num_args = 0; /* True if wrong number of arguments */ 001122 int is_agg = 0; /* True if is an aggregate function */ 001123 const char *zId; /* The function name. */ 001124 FuncDef *pDef; /* Information about the function */ 001125 u8 enc = ENC(pParse->db); /* The database encoding */ 001126 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin)); 001127 #ifndef SQLITE_OMIT_WINDOWFUNC 001128 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0); 001129 #endif 001130 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) ); 001131 assert( pExpr->pLeft==0 || pExpr->pLeft->op==TK_ORDER ); 001132 zId = pExpr->u.zToken; 001133 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0); 001134 if( pDef==0 ){ 001135 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0); 001136 if( pDef==0 ){ 001137 no_such_func = 1; 001138 }else{ 001139 wrong_num_args = 1; 001140 } 001141 }else{ 001142 is_agg = pDef->xFinalize!=0; 001143 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){ 001144 ExprSetProperty(pExpr, EP_Unlikely); 001145 if( n==2 ){ 001146 pExpr->iTable = exprProbability(pList->a[1].pExpr); 001147 if( pExpr->iTable<0 ){ 001148 sqlite3ErrorMsg(pParse, 001149 "second argument to %#T() must be a " 001150 "constant between 0.0 and 1.0", pExpr); 001151 pNC->nNcErr++; 001152 } 001153 }else{ 001154 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is 001155 ** equivalent to likelihood(X, 0.0625). 001156 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is 001157 ** short-hand for likelihood(X,0.0625). 001158 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand 001159 ** for likelihood(X,0.9375). 001160 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent 001161 ** to likelihood(X,0.9375). */ 001162 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */ 001163 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120; 001164 } 001165 } 001166 #ifndef SQLITE_OMIT_AUTHORIZATION 001167 { 001168 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0); 001169 if( auth!=SQLITE_OK ){ 001170 if( auth==SQLITE_DENY ){ 001171 sqlite3ErrorMsg(pParse, "not authorized to use function: %#T", 001172 pExpr); 001173 pNC->nNcErr++; 001174 } 001175 pExpr->op = TK_NULL; 001176 return WRC_Prune; 001177 } 001178 } 001179 #endif 001180 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){ 001181 /* For the purposes of the EP_ConstFunc flag, date and time 001182 ** functions and other functions that change slowly are considered 001183 ** constant because they are constant for the duration of one query. 001184 ** This allows them to be factored out of inner loops. */ 001185 ExprSetProperty(pExpr,EP_ConstFunc); 001186 } 001187 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){ 001188 /* Clearly non-deterministic functions like random(), but also 001189 ** date/time functions that use 'now', and other functions like 001190 ** sqlite_version() that might change over time cannot be used 001191 ** in an index or generated column. Curiously, they can be used 001192 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all 001193 ** all this. */ 001194 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions", 001195 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr); 001196 }else{ 001197 assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */ 001198 pExpr->op2 = pNC->ncFlags & NC_SelfRef; 001199 if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL); 001200 } 001201 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 001202 && pParse->nested==0 001203 && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0 001204 ){ 001205 /* Internal-use-only functions are disallowed unless the 001206 ** SQL is being compiled using sqlite3NestedParse() or 001207 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be 001208 ** used to activate internal functions for testing purposes */ 001209 no_such_func = 1; 001210 pDef = 0; 001211 }else 001212 if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 001213 && !IN_RENAME_OBJECT 001214 ){ 001215 sqlite3ExprFunctionUsable(pParse, pExpr, pDef); 001216 } 001217 } 001218 001219 if( 0==IN_RENAME_OBJECT ){ 001220 #ifndef SQLITE_OMIT_WINDOWFUNC 001221 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX) 001222 || (pDef->xValue==0 && pDef->xInverse==0) 001223 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize) 001224 ); 001225 if( pDef && pDef->xValue==0 && pWin ){ 001226 sqlite3ErrorMsg(pParse, 001227 "%#T() may not be used as a window function", pExpr 001228 ); 001229 pNC->nNcErr++; 001230 }else if( 001231 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) 001232 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin) 001233 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0) 001234 ){ 001235 const char *zType; 001236 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){ 001237 zType = "window"; 001238 }else{ 001239 zType = "aggregate"; 001240 } 001241 sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr); 001242 pNC->nNcErr++; 001243 is_agg = 0; 001244 } 001245 #else 001246 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){ 001247 sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr); 001248 pNC->nNcErr++; 001249 is_agg = 0; 001250 } 001251 #endif 001252 else if( no_such_func && pParse->db->init.busy==0 001253 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 001254 && pParse->explain==0 001255 #endif 001256 ){ 001257 sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr); 001258 pNC->nNcErr++; 001259 }else if( wrong_num_args ){ 001260 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()", 001261 pExpr); 001262 pNC->nNcErr++; 001263 } 001264 #ifndef SQLITE_OMIT_WINDOWFUNC 001265 else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){ 001266 sqlite3ErrorMsg(pParse, 001267 "FILTER may not be used with non-aggregate %#T()", 001268 pExpr 001269 ); 001270 pNC->nNcErr++; 001271 } 001272 #endif 001273 else if( is_agg==0 && pExpr->pLeft ){ 001274 sqlite3ExprOrderByAggregateError(pParse, pExpr); 001275 pNC->nNcErr++; 001276 } 001277 if( is_agg ){ 001278 /* Window functions may not be arguments of aggregate functions. 001279 ** Or arguments of other window functions. But aggregate functions 001280 ** may be arguments for window functions. */ 001281 #ifndef SQLITE_OMIT_WINDOWFUNC 001282 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0)); 001283 #else 001284 pNC->ncFlags &= ~NC_AllowAgg; 001285 #endif 001286 } 001287 } 001288 else if( ExprHasProperty(pExpr, EP_WinFunc) || pExpr->pLeft ){ 001289 is_agg = 1; 001290 } 001291 sqlite3WalkExprList(pWalker, pList); 001292 if( is_agg ){ 001293 if( pExpr->pLeft ){ 001294 assert( pExpr->pLeft->op==TK_ORDER ); 001295 assert( ExprUseXList(pExpr->pLeft) ); 001296 sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList); 001297 } 001298 #ifndef SQLITE_OMIT_WINDOWFUNC 001299 if( pWin ){ 001300 Select *pSel = pNC->pWinSelect; 001301 assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) ); 001302 if( IN_RENAME_OBJECT==0 ){ 001303 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef); 001304 if( pParse->db->mallocFailed ) break; 001305 } 001306 sqlite3WalkExprList(pWalker, pWin->pPartition); 001307 sqlite3WalkExprList(pWalker, pWin->pOrderBy); 001308 sqlite3WalkExpr(pWalker, pWin->pFilter); 001309 sqlite3WindowLink(pSel, pWin); 001310 pNC->ncFlags |= NC_HasWin; 001311 }else 001312 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001313 { 001314 NameContext *pNC2; /* For looping up thru outer contexts */ 001315 pExpr->op = TK_AGG_FUNCTION; 001316 pExpr->op2 = 0; 001317 #ifndef SQLITE_OMIT_WINDOWFUNC 001318 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 001319 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter); 001320 } 001321 #endif 001322 pNC2 = pNC; 001323 while( pNC2 001324 && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0 001325 ){ 001326 pExpr->op2 += (1 + pNC2->nNestedSelect); 001327 pNC2 = pNC2->pNext; 001328 } 001329 assert( pDef!=0 || IN_RENAME_OBJECT ); 001330 if( pNC2 && pDef ){ 001331 pExpr->op2 += pNC2->nNestedSelect; 001332 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg ); 001333 assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg ); 001334 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 ); 001335 testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 ); 001336 pNC2->ncFlags |= NC_HasAgg 001337 | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER) 001338 & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER)); 001339 } 001340 } 001341 pNC->ncFlags |= savedAllowFlags; 001342 } 001343 /* FIX ME: Compute pExpr->affinity based on the expected return 001344 ** type of the function 001345 */ 001346 return WRC_Prune; 001347 } 001348 #ifndef SQLITE_OMIT_SUBQUERY 001349 case TK_SELECT: 001350 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS ); 001351 #endif 001352 case TK_IN: { 001353 testcase( pExpr->op==TK_IN ); 001354 if( ExprUseXSelect(pExpr) ){ 001355 int nRef = pNC->nRef; 001356 testcase( pNC->ncFlags & NC_IsCheck ); 001357 testcase( pNC->ncFlags & NC_PartIdx ); 001358 testcase( pNC->ncFlags & NC_IdxExpr ); 001359 testcase( pNC->ncFlags & NC_GenCol ); 001360 assert( pExpr->x.pSelect ); 001361 if( pNC->ncFlags & NC_SelfRef ){ 001362 notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr); 001363 }else{ 001364 sqlite3WalkSelect(pWalker, pExpr->x.pSelect); 001365 } 001366 assert( pNC->nRef>=nRef ); 001367 if( nRef!=pNC->nRef ){ 001368 ExprSetProperty(pExpr, EP_VarSelect); 001369 pExpr->x.pSelect->selFlags |= SF_Correlated; 001370 } 001371 pNC->ncFlags |= NC_Subquery; 001372 } 001373 break; 001374 } 001375 case TK_VARIABLE: { 001376 testcase( pNC->ncFlags & NC_IsCheck ); 001377 testcase( pNC->ncFlags & NC_PartIdx ); 001378 testcase( pNC->ncFlags & NC_IdxExpr ); 001379 testcase( pNC->ncFlags & NC_GenCol ); 001380 sqlite3ResolveNotValid(pParse, pNC, "parameters", 001381 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr); 001382 break; 001383 } 001384 case TK_IS: 001385 case TK_ISNOT: { 001386 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight); 001387 assert( !ExprHasProperty(pExpr, EP_Reduced) ); 001388 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE", 001389 ** and "x IS NOT FALSE". */ 001390 if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){ 001391 int rc = resolveExprStep(pWalker, pRight); 001392 if( rc==WRC_Abort ) return WRC_Abort; 001393 if( pRight->op==TK_TRUEFALSE ){ 001394 pExpr->op2 = pExpr->op; 001395 pExpr->op = TK_TRUTH; 001396 return WRC_Continue; 001397 } 001398 } 001399 /* no break */ deliberate_fall_through 001400 } 001401 case TK_BETWEEN: 001402 case TK_EQ: 001403 case TK_NE: 001404 case TK_LT: 001405 case TK_LE: 001406 case TK_GT: 001407 case TK_GE: { 001408 int nLeft, nRight; 001409 if( pParse->db->mallocFailed ) break; 001410 assert( pExpr->pLeft!=0 ); 001411 nLeft = sqlite3ExprVectorSize(pExpr->pLeft); 001412 if( pExpr->op==TK_BETWEEN ){ 001413 assert( ExprUseXList(pExpr) ); 001414 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr); 001415 if( nRight==nLeft ){ 001416 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr); 001417 } 001418 }else{ 001419 assert( pExpr->pRight!=0 ); 001420 nRight = sqlite3ExprVectorSize(pExpr->pRight); 001421 } 001422 if( nLeft!=nRight ){ 001423 testcase( pExpr->op==TK_EQ ); 001424 testcase( pExpr->op==TK_NE ); 001425 testcase( pExpr->op==TK_LT ); 001426 testcase( pExpr->op==TK_LE ); 001427 testcase( pExpr->op==TK_GT ); 001428 testcase( pExpr->op==TK_GE ); 001429 testcase( pExpr->op==TK_IS ); 001430 testcase( pExpr->op==TK_ISNOT ); 001431 testcase( pExpr->op==TK_BETWEEN ); 001432 sqlite3ErrorMsg(pParse, "row value misused"); 001433 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr); 001434 } 001435 break; 001436 } 001437 } 001438 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 ); 001439 return pParse->nErr ? WRC_Abort : WRC_Continue; 001440 } 001441 001442 /* 001443 ** pEList is a list of expressions which are really the result set of the 001444 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause. 001445 ** This routine checks to see if pE is a simple identifier which corresponds 001446 ** to the AS-name of one of the terms of the expression list. If it is, 001447 ** this routine return an integer between 1 and N where N is the number of 001448 ** elements in pEList, corresponding to the matching entry. If there is 001449 ** no match, or if pE is not a simple identifier, then this routine 001450 ** return 0. 001451 ** 001452 ** pEList has been resolved. pE has not. 001453 */ 001454 static int resolveAsName( 001455 Parse *pParse, /* Parsing context for error messages */ 001456 ExprList *pEList, /* List of expressions to scan */ 001457 Expr *pE /* Expression we are trying to match */ 001458 ){ 001459 int i; /* Loop counter */ 001460 001461 UNUSED_PARAMETER(pParse); 001462 001463 if( pE->op==TK_ID ){ 001464 const char *zCol; 001465 assert( !ExprHasProperty(pE, EP_IntValue) ); 001466 zCol = pE->u.zToken; 001467 for(i=0; i<pEList->nExpr; i++){ 001468 if( pEList->a[i].fg.eEName==ENAME_NAME 001469 && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0 001470 ){ 001471 return i+1; 001472 } 001473 } 001474 } 001475 return 0; 001476 } 001477 001478 /* 001479 ** pE is a pointer to an expression which is a single term in the 001480 ** ORDER BY of a compound SELECT. The expression has not been 001481 ** name resolved. 001482 ** 001483 ** At the point this routine is called, we already know that the 001484 ** ORDER BY term is not an integer index into the result set. That 001485 ** case is handled by the calling routine. 001486 ** 001487 ** Attempt to match pE against result set columns in the left-most 001488 ** SELECT statement. Return the index i of the matching column, 001489 ** as an indication to the caller that it should sort by the i-th column. 001490 ** The left-most column is 1. In other words, the value returned is the 001491 ** same integer value that would be used in the SQL statement to indicate 001492 ** the column. 001493 ** 001494 ** If there is no match, return 0. Return -1 if an error occurs. 001495 */ 001496 static int resolveOrderByTermToExprList( 001497 Parse *pParse, /* Parsing context for error messages */ 001498 Select *pSelect, /* The SELECT statement with the ORDER BY clause */ 001499 Expr *pE /* The specific ORDER BY term */ 001500 ){ 001501 int i; /* Loop counter */ 001502 ExprList *pEList; /* The columns of the result set */ 001503 NameContext nc; /* Name context for resolving pE */ 001504 sqlite3 *db; /* Database connection */ 001505 int rc; /* Return code from subprocedures */ 001506 u8 savedSuppErr; /* Saved value of db->suppressErr */ 001507 001508 assert( sqlite3ExprIsInteger(pE, &i)==0 ); 001509 pEList = pSelect->pEList; 001510 001511 /* Resolve all names in the ORDER BY term expression 001512 */ 001513 memset(&nc, 0, sizeof(nc)); 001514 nc.pParse = pParse; 001515 nc.pSrcList = pSelect->pSrc; 001516 nc.uNC.pEList = pEList; 001517 nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect; 001518 nc.nNcErr = 0; 001519 db = pParse->db; 001520 savedSuppErr = db->suppressErr; 001521 db->suppressErr = 1; 001522 rc = sqlite3ResolveExprNames(&nc, pE); 001523 db->suppressErr = savedSuppErr; 001524 if( rc ) return 0; 001525 001526 /* Try to match the ORDER BY expression against an expression 001527 ** in the result set. Return an 1-based index of the matching 001528 ** result-set entry. 001529 */ 001530 for(i=0; i<pEList->nExpr; i++){ 001531 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){ 001532 return i+1; 001533 } 001534 } 001535 001536 /* If no match, return 0. */ 001537 return 0; 001538 } 001539 001540 /* 001541 ** Generate an ORDER BY or GROUP BY term out-of-range error. 001542 */ 001543 static void resolveOutOfRangeError( 001544 Parse *pParse, /* The error context into which to write the error */ 001545 const char *zType, /* "ORDER" or "GROUP" */ 001546 int i, /* The index (1-based) of the term out of range */ 001547 int mx, /* Largest permissible value of i */ 001548 Expr *pError /* Associate the error with the expression */ 001549 ){ 001550 sqlite3ErrorMsg(pParse, 001551 "%r %s BY term out of range - should be " 001552 "between 1 and %d", i, zType, mx); 001553 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError); 001554 } 001555 001556 /* 001557 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify 001558 ** each term of the ORDER BY clause is a constant integer between 1 001559 ** and N where N is the number of columns in the compound SELECT. 001560 ** 001561 ** ORDER BY terms that are already an integer between 1 and N are 001562 ** unmodified. ORDER BY terms that are integers outside the range of 001563 ** 1 through N generate an error. ORDER BY terms that are expressions 001564 ** are matched against result set expressions of compound SELECT 001565 ** beginning with the left-most SELECT and working toward the right. 001566 ** At the first match, the ORDER BY expression is transformed into 001567 ** the integer column number. 001568 ** 001569 ** Return the number of errors seen. 001570 */ 001571 static int resolveCompoundOrderBy( 001572 Parse *pParse, /* Parsing context. Leave error messages here */ 001573 Select *pSelect /* The SELECT statement containing the ORDER BY */ 001574 ){ 001575 int i; 001576 ExprList *pOrderBy; 001577 ExprList *pEList; 001578 sqlite3 *db; 001579 int moreToDo = 1; 001580 001581 pOrderBy = pSelect->pOrderBy; 001582 if( pOrderBy==0 ) return 0; 001583 db = pParse->db; 001584 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 001585 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); 001586 return 1; 001587 } 001588 for(i=0; i<pOrderBy->nExpr; i++){ 001589 pOrderBy->a[i].fg.done = 0; 001590 } 001591 pSelect->pNext = 0; 001592 while( pSelect->pPrior ){ 001593 pSelect->pPrior->pNext = pSelect; 001594 pSelect = pSelect->pPrior; 001595 } 001596 while( pSelect && moreToDo ){ 001597 struct ExprList_item *pItem; 001598 moreToDo = 0; 001599 pEList = pSelect->pEList; 001600 assert( pEList!=0 ); 001601 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 001602 int iCol = -1; 001603 Expr *pE, *pDup; 001604 if( pItem->fg.done ) continue; 001605 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr); 001606 if( NEVER(pE==0) ) continue; 001607 if( sqlite3ExprIsInteger(pE, &iCol) ){ 001608 if( iCol<=0 || iCol>pEList->nExpr ){ 001609 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE); 001610 return 1; 001611 } 001612 }else{ 001613 iCol = resolveAsName(pParse, pEList, pE); 001614 if( iCol==0 ){ 001615 /* Now test if expression pE matches one of the values returned 001616 ** by pSelect. In the usual case this is done by duplicating the 001617 ** expression, resolving any symbols in it, and then comparing 001618 ** it against each expression returned by the SELECT statement. 001619 ** Once the comparisons are finished, the duplicate expression 001620 ** is deleted. 001621 ** 001622 ** If this is running as part of an ALTER TABLE operation and 001623 ** the symbols resolve successfully, also resolve the symbols in the 001624 ** actual expression. This allows the code in alter.c to modify 001625 ** column references within the ORDER BY expression as required. */ 001626 pDup = sqlite3ExprDup(db, pE, 0); 001627 if( !db->mallocFailed ){ 001628 assert(pDup); 001629 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup); 001630 if( IN_RENAME_OBJECT && iCol>0 ){ 001631 resolveOrderByTermToExprList(pParse, pSelect, pE); 001632 } 001633 } 001634 sqlite3ExprDelete(db, pDup); 001635 } 001636 } 001637 if( iCol>0 ){ 001638 /* Convert the ORDER BY term into an integer column number iCol, 001639 ** taking care to preserve the COLLATE clause if it exists. */ 001640 if( !IN_RENAME_OBJECT ){ 001641 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0); 001642 if( pNew==0 ) return 1; 001643 pNew->flags |= EP_IntValue; 001644 pNew->u.iValue = iCol; 001645 if( pItem->pExpr==pE ){ 001646 pItem->pExpr = pNew; 001647 }else{ 001648 Expr *pParent = pItem->pExpr; 001649 assert( pParent->op==TK_COLLATE ); 001650 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft; 001651 assert( pParent->pLeft==pE ); 001652 pParent->pLeft = pNew; 001653 } 001654 sqlite3ExprDelete(db, pE); 001655 pItem->u.x.iOrderByCol = (u16)iCol; 001656 } 001657 pItem->fg.done = 1; 001658 }else{ 001659 moreToDo = 1; 001660 } 001661 } 001662 pSelect = pSelect->pNext; 001663 } 001664 for(i=0; i<pOrderBy->nExpr; i++){ 001665 if( pOrderBy->a[i].fg.done==0 ){ 001666 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " 001667 "column in the result set", i+1); 001668 return 1; 001669 } 001670 } 001671 return 0; 001672 } 001673 001674 /* 001675 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of 001676 ** the SELECT statement pSelect. If any term is reference to a 001677 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol 001678 ** field) then convert that term into a copy of the corresponding result set 001679 ** column. 001680 ** 001681 ** If any errors are detected, add an error message to pParse and 001682 ** return non-zero. Return zero if no errors are seen. 001683 */ 001684 int sqlite3ResolveOrderGroupBy( 001685 Parse *pParse, /* Parsing context. Leave error messages here */ 001686 Select *pSelect, /* The SELECT statement containing the clause */ 001687 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ 001688 const char *zType /* "ORDER" or "GROUP" */ 001689 ){ 001690 int i; 001691 sqlite3 *db = pParse->db; 001692 ExprList *pEList; 001693 struct ExprList_item *pItem; 001694 001695 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0; 001696 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 001697 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); 001698 return 1; 001699 } 001700 pEList = pSelect->pEList; 001701 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */ 001702 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 001703 if( pItem->u.x.iOrderByCol ){ 001704 if( pItem->u.x.iOrderByCol>pEList->nExpr ){ 001705 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0); 001706 return 1; 001707 } 001708 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0); 001709 } 001710 } 001711 return 0; 001712 } 001713 001714 #ifndef SQLITE_OMIT_WINDOWFUNC 001715 /* 001716 ** Walker callback for windowRemoveExprFromSelect(). 001717 */ 001718 static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){ 001719 UNUSED_PARAMETER(pWalker); 001720 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 001721 Window *pWin = pExpr->y.pWin; 001722 sqlite3WindowUnlinkFromSelect(pWin); 001723 } 001724 return WRC_Continue; 001725 } 001726 001727 /* 001728 ** Remove any Window objects owned by the expression pExpr from the 001729 ** Select.pWin list of Select object pSelect. 001730 */ 001731 static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){ 001732 if( pSelect->pWin ){ 001733 Walker sWalker; 001734 memset(&sWalker, 0, sizeof(Walker)); 001735 sWalker.xExprCallback = resolveRemoveWindowsCb; 001736 sWalker.u.pSelect = pSelect; 001737 sqlite3WalkExpr(&sWalker, pExpr); 001738 } 001739 } 001740 #else 001741 # define windowRemoveExprFromSelect(a, b) 001742 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001743 001744 /* 001745 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect. 001746 ** The Name context of the SELECT statement is pNC. zType is either 001747 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is. 001748 ** 001749 ** This routine resolves each term of the clause into an expression. 001750 ** If the order-by term is an integer I between 1 and N (where N is the 001751 ** number of columns in the result set of the SELECT) then the expression 001752 ** in the resolution is a copy of the I-th result-set expression. If 001753 ** the order-by term is an identifier that corresponds to the AS-name of 001754 ** a result-set expression, then the term resolves to a copy of the 001755 ** result-set expression. Otherwise, the expression is resolved in 001756 ** the usual way - using sqlite3ResolveExprNames(). 001757 ** 001758 ** This routine returns the number of errors. If errors occur, then 001759 ** an appropriate error message might be left in pParse. (OOM errors 001760 ** excepted.) 001761 */ 001762 static int resolveOrderGroupBy( 001763 NameContext *pNC, /* The name context of the SELECT statement */ 001764 Select *pSelect, /* The SELECT statement holding pOrderBy */ 001765 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */ 001766 const char *zType /* Either "ORDER" or "GROUP", as appropriate */ 001767 ){ 001768 int i, j; /* Loop counters */ 001769 int iCol; /* Column number */ 001770 struct ExprList_item *pItem; /* A term of the ORDER BY clause */ 001771 Parse *pParse; /* Parsing context */ 001772 int nResult; /* Number of terms in the result set */ 001773 001774 assert( pOrderBy!=0 ); 001775 nResult = pSelect->pEList->nExpr; 001776 pParse = pNC->pParse; 001777 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){ 001778 Expr *pE = pItem->pExpr; 001779 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE); 001780 if( NEVER(pE2==0) ) continue; 001781 if( zType[0]!='G' ){ 001782 iCol = resolveAsName(pParse, pSelect->pEList, pE2); 001783 if( iCol>0 ){ 001784 /* If an AS-name match is found, mark this ORDER BY column as being 001785 ** a copy of the iCol-th result-set column. The subsequent call to 001786 ** sqlite3ResolveOrderGroupBy() will convert the expression to a 001787 ** copy of the iCol-th result-set expression. */ 001788 pItem->u.x.iOrderByCol = (u16)iCol; 001789 continue; 001790 } 001791 } 001792 if( sqlite3ExprIsInteger(pE2, &iCol) ){ 001793 /* The ORDER BY term is an integer constant. Again, set the column 001794 ** number so that sqlite3ResolveOrderGroupBy() will convert the 001795 ** order-by term to a copy of the result-set expression */ 001796 if( iCol<1 || iCol>0xffff ){ 001797 resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2); 001798 return 1; 001799 } 001800 pItem->u.x.iOrderByCol = (u16)iCol; 001801 continue; 001802 } 001803 001804 /* Otherwise, treat the ORDER BY term as an ordinary expression */ 001805 pItem->u.x.iOrderByCol = 0; 001806 if( sqlite3ResolveExprNames(pNC, pE) ){ 001807 return 1; 001808 } 001809 for(j=0; j<pSelect->pEList->nExpr; j++){ 001810 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){ 001811 /* Since this expression is being changed into a reference 001812 ** to an identical expression in the result set, remove all Window 001813 ** objects belonging to the expression from the Select.pWin list. */ 001814 windowRemoveExprFromSelect(pSelect, pE); 001815 pItem->u.x.iOrderByCol = j+1; 001816 } 001817 } 001818 } 001819 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType); 001820 } 001821 001822 /* 001823 ** Resolve names in the SELECT statement p and all of its descendants. 001824 */ 001825 static int resolveSelectStep(Walker *pWalker, Select *p){ 001826 NameContext *pOuterNC; /* Context that contains this SELECT */ 001827 NameContext sNC; /* Name context of this SELECT */ 001828 int isCompound; /* True if p is a compound select */ 001829 int nCompound; /* Number of compound terms processed so far */ 001830 Parse *pParse; /* Parsing context */ 001831 int i; /* Loop counter */ 001832 ExprList *pGroupBy; /* The GROUP BY clause */ 001833 Select *pLeftmost; /* Left-most of SELECT of a compound */ 001834 sqlite3 *db; /* Database connection */ 001835 001836 001837 assert( p!=0 ); 001838 if( p->selFlags & SF_Resolved ){ 001839 return WRC_Prune; 001840 } 001841 pOuterNC = pWalker->u.pNC; 001842 pParse = pWalker->pParse; 001843 db = pParse->db; 001844 001845 /* Normally sqlite3SelectExpand() will be called first and will have 001846 ** already expanded this SELECT. However, if this is a subquery within 001847 ** an expression, sqlite3ResolveExprNames() will be called without a 001848 ** prior call to sqlite3SelectExpand(). When that happens, let 001849 ** sqlite3SelectPrep() do all of the processing for this SELECT. 001850 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and 001851 ** this routine in the correct order. 001852 */ 001853 if( (p->selFlags & SF_Expanded)==0 ){ 001854 sqlite3SelectPrep(pParse, p, pOuterNC); 001855 return pParse->nErr ? WRC_Abort : WRC_Prune; 001856 } 001857 001858 isCompound = p->pPrior!=0; 001859 nCompound = 0; 001860 pLeftmost = p; 001861 while( p ){ 001862 assert( (p->selFlags & SF_Expanded)!=0 ); 001863 assert( (p->selFlags & SF_Resolved)==0 ); 001864 p->selFlags |= SF_Resolved; 001865 001866 /* Resolve the expressions in the LIMIT and OFFSET clauses. These 001867 ** are not allowed to refer to any names, so pass an empty NameContext. 001868 */ 001869 memset(&sNC, 0, sizeof(sNC)); 001870 sNC.pParse = pParse; 001871 sNC.pWinSelect = p; 001872 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){ 001873 return WRC_Abort; 001874 } 001875 001876 /* If the SF_Converted flags is set, then this Select object was 001877 ** was created by the convertCompoundSelectToSubquery() function. 001878 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved 001879 ** as if it were part of the sub-query, not the parent. This block 001880 ** moves the pOrderBy down to the sub-query. It will be moved back 001881 ** after the names have been resolved. */ 001882 if( p->selFlags & SF_Converted ){ 001883 Select *pSub = p->pSrc->a[0].pSelect; 001884 assert( p->pSrc->nSrc==1 && p->pOrderBy ); 001885 assert( pSub->pPrior && pSub->pOrderBy==0 ); 001886 pSub->pOrderBy = p->pOrderBy; 001887 p->pOrderBy = 0; 001888 } 001889 001890 /* Recursively resolve names in all subqueries in the FROM clause 001891 */ 001892 if( pOuterNC ) pOuterNC->nNestedSelect++; 001893 for(i=0; i<p->pSrc->nSrc; i++){ 001894 SrcItem *pItem = &p->pSrc->a[i]; 001895 assert( pItem->zName!=0 || pItem->pSelect!=0 );/* Test of tag-20240424-1*/ 001896 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){ 001897 int nRef = pOuterNC ? pOuterNC->nRef : 0; 001898 const char *zSavedContext = pParse->zAuthContext; 001899 001900 if( pItem->zName ) pParse->zAuthContext = pItem->zName; 001901 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC); 001902 pParse->zAuthContext = zSavedContext; 001903 if( pParse->nErr ) return WRC_Abort; 001904 assert( db->mallocFailed==0 ); 001905 001906 /* If the number of references to the outer context changed when 001907 ** expressions in the sub-select were resolved, the sub-select 001908 ** is correlated. It is not required to check the refcount on any 001909 ** but the innermost outer context object, as lookupName() increments 001910 ** the refcount on all contexts between the current one and the 001911 ** context containing the column when it resolves a name. */ 001912 if( pOuterNC ){ 001913 assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef ); 001914 pItem->fg.isCorrelated = (pOuterNC->nRef>nRef); 001915 } 001916 } 001917 } 001918 if( pOuterNC && ALWAYS(pOuterNC->nNestedSelect>0) ){ 001919 pOuterNC->nNestedSelect--; 001920 } 001921 001922 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to 001923 ** resolve the result-set expression list. 001924 */ 001925 sNC.ncFlags = NC_AllowAgg|NC_AllowWin; 001926 sNC.pSrcList = p->pSrc; 001927 sNC.pNext = pOuterNC; 001928 001929 /* Resolve names in the result set. */ 001930 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort; 001931 sNC.ncFlags &= ~NC_AllowWin; 001932 001933 /* If there are no aggregate functions in the result-set, and no GROUP BY 001934 ** expression, do not allow aggregates in any of the other expressions. 001935 */ 001936 assert( (p->selFlags & SF_Aggregate)==0 ); 001937 pGroupBy = p->pGroupBy; 001938 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){ 001939 assert( NC_MinMaxAgg==SF_MinMaxAgg ); 001940 assert( NC_OrderAgg==SF_OrderByReqd ); 001941 p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg)); 001942 }else{ 001943 sNC.ncFlags &= ~NC_AllowAgg; 001944 } 001945 001946 /* Add the output column list to the name-context before parsing the 001947 ** other expressions in the SELECT statement. This is so that 001948 ** expressions in the WHERE clause (etc.) can refer to expressions by 001949 ** aliases in the result set. 001950 ** 001951 ** Minor point: If this is the case, then the expression will be 001952 ** re-evaluated for each reference to it. 001953 */ 001954 assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 ); 001955 sNC.uNC.pEList = p->pEList; 001956 sNC.ncFlags |= NC_UEList; 001957 if( p->pHaving ){ 001958 if( (p->selFlags & SF_Aggregate)==0 ){ 001959 sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query"); 001960 return WRC_Abort; 001961 } 001962 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort; 001963 } 001964 sNC.ncFlags |= NC_Where; 001965 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort; 001966 sNC.ncFlags &= ~NC_Where; 001967 001968 /* Resolve names in table-valued-function arguments */ 001969 for(i=0; i<p->pSrc->nSrc; i++){ 001970 SrcItem *pItem = &p->pSrc->a[i]; 001971 if( pItem->fg.isTabFunc 001972 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg) 001973 ){ 001974 return WRC_Abort; 001975 } 001976 } 001977 001978 #ifndef SQLITE_OMIT_WINDOWFUNC 001979 if( IN_RENAME_OBJECT ){ 001980 Window *pWin; 001981 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){ 001982 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy) 001983 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition) 001984 ){ 001985 return WRC_Abort; 001986 } 001987 } 001988 } 001989 #endif 001990 001991 /* The ORDER BY and GROUP BY clauses may not refer to terms in 001992 ** outer queries 001993 */ 001994 sNC.pNext = 0; 001995 sNC.ncFlags |= NC_AllowAgg|NC_AllowWin; 001996 001997 /* If this is a converted compound query, move the ORDER BY clause from 001998 ** the sub-query back to the parent query. At this point each term 001999 ** within the ORDER BY clause has been transformed to an integer value. 002000 ** These integers will be replaced by copies of the corresponding result 002001 ** set expressions by the call to resolveOrderGroupBy() below. */ 002002 if( p->selFlags & SF_Converted ){ 002003 Select *pSub = p->pSrc->a[0].pSelect; 002004 p->pOrderBy = pSub->pOrderBy; 002005 pSub->pOrderBy = 0; 002006 } 002007 002008 /* Process the ORDER BY clause for singleton SELECT statements. 002009 ** The ORDER BY clause for compounds SELECT statements is handled 002010 ** below, after all of the result-sets for all of the elements of 002011 ** the compound have been resolved. 002012 ** 002013 ** If there is an ORDER BY clause on a term of a compound-select other 002014 ** than the right-most term, then that is a syntax error. But the error 002015 ** is not detected until much later, and so we need to go ahead and 002016 ** resolve those symbols on the incorrect ORDER BY for consistency. 002017 */ 002018 if( p->pOrderBy!=0 002019 && isCompound<=nCompound /* Defer right-most ORDER BY of a compound */ 002020 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") 002021 ){ 002022 return WRC_Abort; 002023 } 002024 if( db->mallocFailed ){ 002025 return WRC_Abort; 002026 } 002027 sNC.ncFlags &= ~NC_AllowWin; 002028 002029 /* Resolve the GROUP BY clause. At the same time, make sure 002030 ** the GROUP BY clause does not contain aggregate functions. 002031 */ 002032 if( pGroupBy ){ 002033 struct ExprList_item *pItem; 002034 002035 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){ 002036 return WRC_Abort; 002037 } 002038 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){ 002039 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){ 002040 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in " 002041 "the GROUP BY clause"); 002042 return WRC_Abort; 002043 } 002044 } 002045 } 002046 002047 /* If this is part of a compound SELECT, check that it has the right 002048 ** number of expressions in the select list. */ 002049 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){ 002050 sqlite3SelectWrongNumTermsError(pParse, p->pNext); 002051 return WRC_Abort; 002052 } 002053 002054 /* Advance to the next term of the compound 002055 */ 002056 p = p->pPrior; 002057 nCompound++; 002058 } 002059 002060 /* Resolve the ORDER BY on a compound SELECT after all terms of 002061 ** the compound have been resolved. 002062 */ 002063 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){ 002064 return WRC_Abort; 002065 } 002066 002067 return WRC_Prune; 002068 } 002069 002070 /* 002071 ** This routine walks an expression tree and resolves references to 002072 ** table columns and result-set columns. At the same time, do error 002073 ** checking on function usage and set a flag if any aggregate functions 002074 ** are seen. 002075 ** 002076 ** To resolve table columns references we look for nodes (or subtrees) of the 002077 ** form X.Y.Z or Y.Z or just Z where 002078 ** 002079 ** X: The name of a database. Ex: "main" or "temp" or 002080 ** the symbolic name assigned to an ATTACH-ed database. 002081 ** 002082 ** Y: The name of a table in a FROM clause. Or in a trigger 002083 ** one of the special names "old" or "new". 002084 ** 002085 ** Z: The name of a column in table Y. 002086 ** 002087 ** The node at the root of the subtree is modified as follows: 002088 ** 002089 ** Expr.op Changed to TK_COLUMN 002090 ** Expr.pTab Points to the Table object for X.Y 002091 ** Expr.iColumn The column index in X.Y. -1 for the rowid. 002092 ** Expr.iTable The VDBE cursor number for X.Y 002093 ** 002094 ** 002095 ** To resolve result-set references, look for expression nodes of the 002096 ** form Z (with no X and Y prefix) where the Z matches the right-hand 002097 ** size of an AS clause in the result-set of a SELECT. The Z expression 002098 ** is replaced by a copy of the left-hand side of the result-set expression. 002099 ** Table-name and function resolution occurs on the substituted expression 002100 ** tree. For example, in: 002101 ** 002102 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x; 002103 ** 002104 ** The "x" term of the order by is replaced by "a+b" to render: 002105 ** 002106 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b; 002107 ** 002108 ** Function calls are checked to make sure that the function is 002109 ** defined and that the correct number of arguments are specified. 002110 ** If the function is an aggregate function, then the NC_HasAgg flag is 002111 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION. 002112 ** If an expression contains aggregate functions then the EP_Agg 002113 ** property on the expression is set. 002114 ** 002115 ** An error message is left in pParse if anything is amiss. The number 002116 ** if errors is returned. 002117 */ 002118 int sqlite3ResolveExprNames( 002119 NameContext *pNC, /* Namespace to resolve expressions in. */ 002120 Expr *pExpr /* The expression to be analyzed. */ 002121 ){ 002122 int savedHasAgg; 002123 Walker w; 002124 002125 if( pExpr==0 ) return SQLITE_OK; 002126 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg); 002127 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg); 002128 w.pParse = pNC->pParse; 002129 w.xExprCallback = resolveExprStep; 002130 w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep; 002131 w.xSelectCallback2 = 0; 002132 w.u.pNC = pNC; 002133 #if SQLITE_MAX_EXPR_DEPTH>0 002134 w.pParse->nHeight += pExpr->nHeight; 002135 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){ 002136 return SQLITE_ERROR; 002137 } 002138 #endif 002139 assert( pExpr!=0 ); 002140 sqlite3WalkExprNN(&w, pExpr); 002141 #if SQLITE_MAX_EXPR_DEPTH>0 002142 w.pParse->nHeight -= pExpr->nHeight; 002143 #endif 002144 assert( EP_Agg==NC_HasAgg ); 002145 assert( EP_Win==NC_HasWin ); 002146 testcase( pNC->ncFlags & NC_HasAgg ); 002147 testcase( pNC->ncFlags & NC_HasWin ); 002148 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) ); 002149 pNC->ncFlags |= savedHasAgg; 002150 return pNC->nNcErr>0 || w.pParse->nErr>0; 002151 } 002152 002153 /* 002154 ** Resolve all names for all expression in an expression list. This is 002155 ** just like sqlite3ResolveExprNames() except that it works for an expression 002156 ** list rather than a single expression. 002157 ** 002158 ** The return value is SQLITE_OK (0) for success or SQLITE_ERROR (1) for a 002159 ** failure. 002160 */ 002161 int sqlite3ResolveExprListNames( 002162 NameContext *pNC, /* Namespace to resolve expressions in. */ 002163 ExprList *pList /* The expression list to be analyzed. */ 002164 ){ 002165 int i; 002166 int savedHasAgg = 0; 002167 Walker w; 002168 if( pList==0 ) return SQLITE_OK; 002169 w.pParse = pNC->pParse; 002170 w.xExprCallback = resolveExprStep; 002171 w.xSelectCallback = resolveSelectStep; 002172 w.xSelectCallback2 = 0; 002173 w.u.pNC = pNC; 002174 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg); 002175 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg); 002176 for(i=0; i<pList->nExpr; i++){ 002177 Expr *pExpr = pList->a[i].pExpr; 002178 if( pExpr==0 ) continue; 002179 #if SQLITE_MAX_EXPR_DEPTH>0 002180 w.pParse->nHeight += pExpr->nHeight; 002181 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){ 002182 return SQLITE_ERROR; 002183 } 002184 #endif 002185 sqlite3WalkExprNN(&w, pExpr); 002186 #if SQLITE_MAX_EXPR_DEPTH>0 002187 w.pParse->nHeight -= pExpr->nHeight; 002188 #endif 002189 assert( EP_Agg==NC_HasAgg ); 002190 assert( EP_Win==NC_HasWin ); 002191 testcase( pNC->ncFlags & NC_HasAgg ); 002192 testcase( pNC->ncFlags & NC_HasWin ); 002193 if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){ 002194 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) ); 002195 savedHasAgg |= pNC->ncFlags & 002196 (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg); 002197 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg); 002198 } 002199 if( w.pParse->nErr>0 ) return SQLITE_ERROR; 002200 } 002201 pNC->ncFlags |= savedHasAgg; 002202 return SQLITE_OK; 002203 } 002204 002205 /* 002206 ** Resolve all names in all expressions of a SELECT and in all 002207 ** descendants of the SELECT, including compounds off of p->pPrior, 002208 ** subqueries in expressions, and subqueries used as FROM clause 002209 ** terms. 002210 ** 002211 ** See sqlite3ResolveExprNames() for a description of the kinds of 002212 ** transformations that occur. 002213 ** 002214 ** All SELECT statements should have been expanded using 002215 ** sqlite3SelectExpand() prior to invoking this routine. 002216 */ 002217 void sqlite3ResolveSelectNames( 002218 Parse *pParse, /* The parser context */ 002219 Select *p, /* The SELECT statement being coded. */ 002220 NameContext *pOuterNC /* Name context for parent SELECT statement */ 002221 ){ 002222 Walker w; 002223 002224 assert( p!=0 ); 002225 w.xExprCallback = resolveExprStep; 002226 w.xSelectCallback = resolveSelectStep; 002227 w.xSelectCallback2 = 0; 002228 w.pParse = pParse; 002229 w.u.pNC = pOuterNC; 002230 sqlite3WalkSelect(&w, p); 002231 } 002232 002233 /* 002234 ** Resolve names in expressions that can only reference a single table 002235 ** or which cannot reference any tables at all. Examples: 002236 ** 002237 ** "type" flag 002238 ** ------------ 002239 ** (1) CHECK constraints NC_IsCheck 002240 ** (2) WHERE clauses on partial indices NC_PartIdx 002241 ** (3) Expressions in indexes on expressions NC_IdxExpr 002242 ** (4) Expression arguments to VACUUM INTO. 0 002243 ** (5) GENERATED ALWAYS as expressions NC_GenCol 002244 ** 002245 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN 002246 ** nodes of the expression is set to -1 and the Expr.iColumn value is 002247 ** set to the column number. In case (4), TK_COLUMN nodes cause an error. 002248 ** 002249 ** Any errors cause an error message to be set in pParse. 002250 */ 002251 int sqlite3ResolveSelfReference( 002252 Parse *pParse, /* Parsing context */ 002253 Table *pTab, /* The table being referenced, or NULL */ 002254 int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */ 002255 Expr *pExpr, /* Expression to resolve. May be NULL. */ 002256 ExprList *pList /* Expression list to resolve. May be NULL. */ 002257 ){ 002258 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */ 002259 NameContext sNC; /* Name context for pParse->pNewTable */ 002260 int rc; 002261 002262 assert( type==0 || pTab!=0 ); 002263 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr 002264 || type==NC_GenCol || pTab==0 ); 002265 memset(&sNC, 0, sizeof(sNC)); 002266 memset(&sSrc, 0, sizeof(sSrc)); 002267 if( pTab ){ 002268 sSrc.nSrc = 1; 002269 sSrc.a[0].zName = pTab->zName; 002270 sSrc.a[0].pTab = pTab; 002271 sSrc.a[0].iCursor = -1; 002272 if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){ 002273 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP 002274 ** schema elements */ 002275 type |= NC_FromDDL; 002276 } 002277 } 002278 sNC.pParse = pParse; 002279 sNC.pSrcList = &sSrc; 002280 sNC.ncFlags = type | NC_IsDDL; 002281 if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc; 002282 if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList); 002283 return rc; 002284 }