blob: 090fa79842f757dd1e6c41688d9bf4e43e601075 [file] [log] [blame]
drh7d10d5a2008-08-20 16:35:10 +00001/*
2** 2008 August 18
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12**
13** This file contains routines used for walking the parser tree and
14** resolve all identifiers by associating them with a particular
15** table and column.
drh7d10d5a2008-08-20 16:35:10 +000016*/
17#include "sqliteInt.h"
18#include <stdlib.h>
19#include <string.h>
20
21/*
drh8b213892008-08-29 02:14:02 +000022** Turn the pExpr expression into an alias for the iCol-th column of the
23** result set in pEList.
24**
25** If the result set column is a simple column reference, then this routine
26** makes an exact copy. But for any other kind of expression, this
27** routine make a copy of the result set column as the argument to the
28** TK_AS operator. The TK_AS operator causes the expression to be
29** evaluated just once and then reused for each alias.
30**
31** The reason for suppressing the TK_AS term when the expression is a simple
32** column reference is so that the column reference will be recognized as
33** usable by indices within the WHERE clause processing logic.
34**
35** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
36** that in a GROUP BY clause, the expression is evaluated twice. Hence:
37**
38** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
39**
40** Is equivalent to:
41**
42** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
43**
44** The result of random()%5 in the GROUP BY clause is probably different
45** from the result in the result-set. We might fix this someday. Or
46** then again, we might not...
47*/
48static void resolveAlias(
49 Parse *pParse, /* Parsing context */
50 ExprList *pEList, /* A result set */
51 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
52 Expr *pExpr, /* Transform this into an alias to the result set */
53 const char *zType /* "GROUP" or "ORDER" or "" */
54){
55 Expr *pOrig; /* The iCol-th column of the result set */
56 Expr *pDup; /* Copy of pOrig */
57 sqlite3 *db; /* The database connection */
58
59 assert( iCol>=0 && iCol<pEList->nExpr );
60 pOrig = pEList->a[iCol].pExpr;
61 assert( pOrig!=0 );
62 assert( pOrig->flags & EP_Resolved );
63 db = pParse->db;
drhb7916a72009-05-27 10:31:29 +000064 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
65 pDup = sqlite3ExprDup(db, pOrig, 0);
drh8b213892008-08-29 02:14:02 +000066 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
67 if( pDup==0 ) return;
68 if( pEList->a[iCol].iAlias==0 ){
drhea678832008-12-10 19:26:22 +000069 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
drh8b213892008-08-29 02:14:02 +000070 }
71 pDup->iTable = pEList->a[iCol].iAlias;
drh0b0745a2009-05-28 12:49:53 +000072 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
73 pDup = sqlite3ExprDup(db, pOrig, 0);
drh2c220452009-05-28 14:34:49 +000074 if( pDup==0 ) return;
drhb7916a72009-05-27 10:31:29 +000075 }else{
drh33e619f2009-05-28 01:00:55 +000076 char *zToken = pOrig->u.zToken;
drh73c0fdc2009-06-15 18:32:36 +000077 assert( zToken!=0 );
drh33e619f2009-05-28 01:00:55 +000078 pOrig->u.zToken = 0;
drhb7916a72009-05-27 10:31:29 +000079 pDup = sqlite3ExprDup(db, pOrig, 0);
drh33e619f2009-05-28 01:00:55 +000080 pOrig->u.zToken = zToken;
drhb7916a72009-05-27 10:31:29 +000081 if( pDup==0 ) return;
drh73c0fdc2009-06-15 18:32:36 +000082 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
83 pDup->flags2 |= EP2_MallocedToken;
84 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
drh8b213892008-08-29 02:14:02 +000085 }
86 if( pExpr->flags & EP_ExpCollate ){
87 pDup->pColl = pExpr->pColl;
88 pDup->flags |= EP_ExpCollate;
89 }
danf6963f92009-11-23 14:39:14 +000090
91 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
92 ** prevents ExprDelete() from deleting the Expr structure itself,
93 ** allowing it to be repopulated by the memcpy() on the following line.
94 */
95 ExprSetProperty(pExpr, EP_Static);
96 sqlite3ExprDelete(db, pExpr);
drh8b213892008-08-29 02:14:02 +000097 memcpy(pExpr, pDup, sizeof(*pExpr));
98 sqlite3DbFree(db, pDup);
99}
100
drhe802c5d2011-10-18 18:10:40 +0000101
102/*
103** Return TRUE if the name zCol occurs anywhere in the USING clause.
104**
105** Return FALSE if the USING clause is NULL or if it does not contain
106** zCol.
107*/
108static int nameInUsingClause(IdList *pUsing, const char *zCol){
109 if( pUsing ){
110 int k;
111 for(k=0; k<pUsing->nId; k++){
112 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
113 }
114 }
115 return 0;
116}
117
118
drh8b213892008-08-29 02:14:02 +0000119/*
drh7d10d5a2008-08-20 16:35:10 +0000120** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
121** that name in the set of source tables in pSrcList and make the pExpr
122** expression node refer back to that source column. The following changes
123** are made to pExpr:
124**
125** pExpr->iDb Set the index in db->aDb[] of the database X
126** (even if X is implied).
127** pExpr->iTable Set to the cursor number for the table obtained
128** from pSrcList.
129** pExpr->pTab Points to the Table structure of X.Y (even if
130** X and/or Y are implied.)
131** pExpr->iColumn Set to the column number within the table.
132** pExpr->op Set to TK_COLUMN.
133** pExpr->pLeft Any expression this points to is deleted
134** pExpr->pRight Any expression this points to is deleted.
135**
drhb7916a72009-05-27 10:31:29 +0000136** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000137** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000138** can be used. The zTable variable is the name of the table (the "Y"). This
139** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000140** means that the form of the name is Z and that columns from any table
141** can be used.
142**
143** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000144** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000145*/
146static int lookupName(
147 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000148 const char *zDb, /* Name of the database containing table, or NULL */
149 const char *zTab, /* Name of table containing column, or NULL */
150 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000151 NameContext *pNC, /* The name context used to resolve the name */
152 Expr *pExpr /* Make this EXPR node point to the selected column */
153){
drh7d10d5a2008-08-20 16:35:10 +0000154 int i, j; /* Loop counters */
155 int cnt = 0; /* Number of matching column names */
156 int cntTab = 0; /* Number of matching table names */
157 sqlite3 *db = pParse->db; /* The database connection */
158 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
159 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
160 NameContext *pTopNC = pNC; /* First namecontext in the list */
161 Schema *pSchema = 0; /* Schema of the expression */
dan2bd93512009-08-31 08:22:46 +0000162 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000163
drhb7916a72009-05-27 10:31:29 +0000164 assert( pNC ); /* the name context cannot be NULL. */
165 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh33e619f2009-05-28 01:00:55 +0000166 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000167
168 /* Initialize the node to no-match */
169 pExpr->iTable = -1;
170 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000171 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000172
173 /* Start at the inner-most context and move outward until a match is found */
174 while( pNC && cnt==0 ){
175 ExprList *pEList;
176 SrcList *pSrcList = pNC->pSrcList;
177
178 if( pSrcList ){
179 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
180 Table *pTab;
181 int iDb;
182 Column *pCol;
183
184 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000185 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000186 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
187 assert( pTab->nCol>0 );
188 if( zTab ){
189 if( pItem->zAlias ){
190 char *zTabName = pItem->zAlias;
191 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
192 }else{
193 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000194 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
195 continue;
196 }
drh7d10d5a2008-08-20 16:35:10 +0000197 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
198 continue;
199 }
200 }
201 }
202 if( 0==(cntTab++) ){
203 pExpr->iTable = pItem->iCursor;
204 pExpr->pTab = pTab;
205 pSchema = pTab->pSchema;
206 pMatch = pItem;
207 }
208 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
209 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
drhe802c5d2011-10-18 18:10:40 +0000210 /* If there has been exactly one prior match and this match
211 ** is for the right-hand table of a NATURAL JOIN or is in a
212 ** USING clause, then skip this match.
213 */
214 if( cnt==1 ){
215 if( pItem->jointype & JT_NATURAL ) continue;
216 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
217 }
drh7d10d5a2008-08-20 16:35:10 +0000218 cnt++;
219 pExpr->iTable = pItem->iCursor;
220 pExpr->pTab = pTab;
221 pMatch = pItem;
222 pSchema = pTab->pSchema;
223 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000224 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000225 break;
226 }
227 }
228 }
229 }
230
231#ifndef SQLITE_OMIT_TRIGGER
232 /* If we have not already resolved the name, then maybe
233 ** it is a new.* or old.* trigger argument reference
234 */
dan165921a2009-08-28 18:53:45 +0000235 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000236 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000237 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000238 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
239 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000240 pExpr->iTable = 1;
241 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000242 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000243 pExpr->iTable = 0;
244 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000245 }
246
247 if( pTab ){
248 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000249 pSchema = pTab->pSchema;
250 cntTab++;
drh25e978d2009-12-29 23:39:04 +0000251 for(iCol=0; iCol<pTab->nCol; iCol++){
252 Column *pCol = &pTab->aCol[iCol];
253 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
254 if( iCol==pTab->iPKey ){
255 iCol = -1;
drh7d10d5a2008-08-20 16:35:10 +0000256 }
drh25e978d2009-12-29 23:39:04 +0000257 break;
drh7d10d5a2008-08-20 16:35:10 +0000258 }
259 }
drh25e978d2009-12-29 23:39:04 +0000260 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
drhc79c7612010-01-01 18:57:48 +0000261 iCol = -1; /* IMP: R-44911-55124 */
drh25e978d2009-12-29 23:39:04 +0000262 }
dan2bd93512009-08-31 08:22:46 +0000263 if( iCol<pTab->nCol ){
264 cnt++;
265 if( iCol<0 ){
266 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000267 }else if( pExpr->iTable==0 ){
268 testcase( iCol==31 );
269 testcase( iCol==32 );
270 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
danbb5f1682009-11-27 12:12:34 +0000271 }else{
272 testcase( iCol==31 );
273 testcase( iCol==32 );
274 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000275 }
shanecea72b22009-09-07 04:38:36 +0000276 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000277 pExpr->pTab = pTab;
278 isTrigger = 1;
279 }
drh7d10d5a2008-08-20 16:35:10 +0000280 }
281 }
282#endif /* !defined(SQLITE_OMIT_TRIGGER) */
283
284 /*
285 ** Perhaps the name is a reference to the ROWID
286 */
287 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
288 cnt = 1;
drhc79c7612010-01-01 18:57:48 +0000289 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
drh7d10d5a2008-08-20 16:35:10 +0000290 pExpr->affinity = SQLITE_AFF_INTEGER;
291 }
292
293 /*
294 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
295 ** might refer to an result-set alias. This happens, for example, when
296 ** we are resolving names in the WHERE clause of the following command:
297 **
298 ** SELECT a+b AS x FROM table WHERE x<10;
299 **
300 ** In cases like this, replace pExpr with a copy of the expression that
301 ** forms the result set entry ("a+b" in the example) and return immediately.
302 ** Note that the expression in the result set should have already been
303 ** resolved by the time the WHERE clause is resolved.
304 */
305 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
306 for(j=0; j<pEList->nExpr; j++){
307 char *zAs = pEList->a[j].zName;
308 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000309 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000310 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000311 assert( pExpr->x.pList==0 );
312 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000313 pOrig = pEList->a[j].pExpr;
314 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
315 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000316 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000317 }
drh8b213892008-08-29 02:14:02 +0000318 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000319 cnt = 1;
320 pMatch = 0;
321 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000322 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000323 }
324 }
325 }
326
327 /* Advance to the next name context. The loop will exit when either
328 ** we have a match (cnt>0) or when we run out of name contexts.
329 */
330 if( cnt==0 ){
331 pNC = pNC->pNext;
332 }
333 }
334
335 /*
336 ** If X and Y are NULL (in other words if only the column name Z is
337 ** supplied) and the value of Z is enclosed in double-quotes, then
338 ** Z is a string literal if it doesn't match any column names. In that
339 ** case, we need to return right away and not make any changes to
340 ** pExpr.
341 **
342 ** Because no reference was made to outer contexts, the pNC->nRef
343 ** fields are not changed in any context.
344 */
drh24fb6272009-05-01 21:13:36 +0000345 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000346 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000347 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000348 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000349 }
350
351 /*
352 ** cnt==0 means there was not match. cnt>1 means there were two or
353 ** more matches. Either way, we have an error.
354 */
355 if( cnt!=1 ){
356 const char *zErr;
357 zErr = cnt==0 ? "no such column" : "ambiguous column name";
358 if( zDb ){
359 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
360 }else if( zTab ){
361 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
362 }else{
363 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
364 }
dan1db95102010-06-28 10:15:19 +0000365 pParse->checkSchema = 1;
drh7d10d5a2008-08-20 16:35:10 +0000366 pTopNC->nErr++;
367 }
368
369 /* If a column from a table in pSrcList is referenced, then record
370 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
371 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
372 ** column number is greater than the number of bits in the bitmask
373 ** then set the high-order bit of the bitmask.
374 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000375 if( pExpr->iColumn>=0 && pMatch!=0 ){
376 int n = pExpr->iColumn;
377 testcase( n==BMS-1 );
378 if( n>=BMS ){
379 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000380 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000381 assert( pMatch->iCursor==pExpr->iTable );
382 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000383 }
384
drh7d10d5a2008-08-20 16:35:10 +0000385 /* Clean up and return
386 */
drh7d10d5a2008-08-20 16:35:10 +0000387 sqlite3ExprDelete(db, pExpr->pLeft);
388 pExpr->pLeft = 0;
389 sqlite3ExprDelete(db, pExpr->pRight);
390 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000391 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000392lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000393 if( cnt==1 ){
394 assert( pNC!=0 );
395 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
396 /* Increment the nRef value on all name contexts from TopNC up to
397 ** the point where the name matched. */
398 for(;;){
399 assert( pTopNC!=0 );
400 pTopNC->nRef++;
401 if( pTopNC==pNC ) break;
402 pTopNC = pTopNC->pNext;
403 }
drhf7828b52009-06-15 23:15:59 +0000404 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000405 } else {
drhf7828b52009-06-15 23:15:59 +0000406 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000407 }
408}
409
410/*
danf7b0b0a2009-10-19 15:52:32 +0000411** Allocate and return a pointer to an expression to load the column iCol
drh9e481652010-04-08 17:35:34 +0000412** from datasource iSrc in SrcList pSrc.
danf7b0b0a2009-10-19 15:52:32 +0000413*/
414Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
415 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
416 if( p ){
417 struct SrcList_item *pItem = &pSrc->a[iSrc];
418 p->pTab = pItem->pTab;
419 p->iTable = pItem->iCursor;
420 if( p->pTab->iPKey==iCol ){
421 p->iColumn = -1;
422 }else{
drh8677d302009-11-04 13:17:14 +0000423 p->iColumn = (ynVar)iCol;
drh7caba662010-04-08 15:01:44 +0000424 testcase( iCol==BMS );
425 testcase( iCol==BMS-1 );
danf7b0b0a2009-10-19 15:52:32 +0000426 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
427 }
428 ExprSetProperty(p, EP_Resolved);
429 }
430 return p;
431}
432
433/*
drh7d10d5a2008-08-20 16:35:10 +0000434** This routine is callback for sqlite3WalkExpr().
435**
436** Resolve symbolic names into TK_COLUMN operators for the current
437** node in the expression tree. Return 0 to continue the search down
438** the tree or 2 to abort the tree walk.
439**
440** This routine also does error checking and name resolution for
441** function names. The operator for aggregate functions is changed
442** to TK_AGG_FUNCTION.
443*/
444static int resolveExprStep(Walker *pWalker, Expr *pExpr){
445 NameContext *pNC;
446 Parse *pParse;
447
drh7d10d5a2008-08-20 16:35:10 +0000448 pNC = pWalker->u.pNC;
449 assert( pNC!=0 );
450 pParse = pNC->pParse;
451 assert( pParse==pWalker->pParse );
452
453 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
454 ExprSetProperty(pExpr, EP_Resolved);
455#ifndef NDEBUG
456 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
457 SrcList *pSrcList = pNC->pSrcList;
458 int i;
459 for(i=0; i<pNC->pSrcList->nSrc; i++){
460 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
461 }
462 }
463#endif
464 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000465
shane273f6192008-10-10 04:34:16 +0000466#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000467 /* The special operator TK_ROW means use the rowid for the first
468 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
469 ** clause processing on UPDATE and DELETE statements.
470 */
471 case TK_ROW: {
472 SrcList *pSrcList = pNC->pSrcList;
473 struct SrcList_item *pItem;
474 assert( pSrcList && pSrcList->nSrc==1 );
475 pItem = pSrcList->a;
476 pExpr->op = TK_COLUMN;
477 pExpr->pTab = pItem->pTab;
478 pExpr->iTable = pItem->iCursor;
479 pExpr->iColumn = -1;
480 pExpr->affinity = SQLITE_AFF_INTEGER;
481 break;
482 }
shane273f6192008-10-10 04:34:16 +0000483#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000484
drh7d10d5a2008-08-20 16:35:10 +0000485 /* A lone identifier is the name of a column.
486 */
487 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000488 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000489 }
490
491 /* A table name and column name: ID.ID
492 ** Or a database, table and column: ID.ID.ID
493 */
494 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000495 const char *zColumn;
496 const char *zTable;
497 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000498 Expr *pRight;
499
500 /* if( pSrcList==0 ) break; */
501 pRight = pExpr->pRight;
502 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000503 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000504 zTable = pExpr->pLeft->u.zToken;
505 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000506 }else{
507 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000508 zDb = pExpr->pLeft->u.zToken;
509 zTable = pRight->pLeft->u.zToken;
510 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000511 }
drhf7828b52009-06-15 23:15:59 +0000512 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000513 }
514
515 /* Resolve function names
516 */
517 case TK_CONST_FUNC:
518 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000519 ExprList *pList = pExpr->x.pList; /* The argument list */
520 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000521 int no_such_func = 0; /* True if no such function exists */
522 int wrong_num_args = 0; /* True if wrong number of arguments */
523 int is_agg = 0; /* True if is an aggregate function */
524 int auth; /* Authorization to use the function */
525 int nId; /* Number of characters in function name */
526 const char *zId; /* The function name. */
527 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000528 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000529
drh73c0fdc2009-06-15 18:32:36 +0000530 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000531 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000532 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000533 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000534 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
535 if( pDef==0 ){
drh89d5d6a2012-04-07 00:09:21 +0000536 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
drh7d10d5a2008-08-20 16:35:10 +0000537 if( pDef==0 ){
538 no_such_func = 1;
539 }else{
540 wrong_num_args = 1;
541 }
542 }else{
543 is_agg = pDef->xFunc==0;
544 }
545#ifndef SQLITE_OMIT_AUTHORIZATION
546 if( pDef ){
547 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
548 if( auth!=SQLITE_OK ){
549 if( auth==SQLITE_DENY ){
550 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
551 pDef->zName);
552 pNC->nErr++;
553 }
554 pExpr->op = TK_NULL;
555 return WRC_Prune;
556 }
557 }
558#endif
559 if( is_agg && !pNC->allowAgg ){
560 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
561 pNC->nErr++;
562 is_agg = 0;
563 }else if( no_such_func ){
564 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
565 pNC->nErr++;
566 }else if( wrong_num_args ){
567 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
568 nId, zId);
569 pNC->nErr++;
570 }
571 if( is_agg ){
572 pExpr->op = TK_AGG_FUNCTION;
573 pNC->hasAgg = 1;
574 }
575 if( is_agg ) pNC->allowAgg = 0;
576 sqlite3WalkExprList(pWalker, pList);
577 if( is_agg ) pNC->allowAgg = 1;
578 /* FIX ME: Compute pExpr->affinity based on the expected return
579 ** type of the function
580 */
581 return WRC_Prune;
582 }
583#ifndef SQLITE_OMIT_SUBQUERY
584 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000585 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000586#endif
587 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000588 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000589 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000590 int nRef = pNC->nRef;
591#ifndef SQLITE_OMIT_CHECK
592 if( pNC->isCheck ){
593 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
594 }
595#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000596 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000597 assert( pNC->nRef>=nRef );
598 if( nRef!=pNC->nRef ){
599 ExprSetProperty(pExpr, EP_VarSelect);
600 }
601 }
602 break;
603 }
604#ifndef SQLITE_OMIT_CHECK
605 case TK_VARIABLE: {
606 if( pNC->isCheck ){
607 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
608 }
609 break;
610 }
611#endif
612 }
613 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
614}
615
616/*
617** pEList is a list of expressions which are really the result set of the
618** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
619** This routine checks to see if pE is a simple identifier which corresponds
620** to the AS-name of one of the terms of the expression list. If it is,
621** this routine return an integer between 1 and N where N is the number of
622** elements in pEList, corresponding to the matching entry. If there is
623** no match, or if pE is not a simple identifier, then this routine
624** return 0.
625**
626** pEList has been resolved. pE has not.
627*/
628static int resolveAsName(
629 Parse *pParse, /* Parsing context for error messages */
630 ExprList *pEList, /* List of expressions to scan */
631 Expr *pE /* Expression we are trying to match */
632){
633 int i; /* Loop counter */
634
shanecf697392009-06-01 16:53:09 +0000635 UNUSED_PARAMETER(pParse);
636
drh73c0fdc2009-06-15 18:32:36 +0000637 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000638 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000639 for(i=0; i<pEList->nExpr; i++){
640 char *zAs = pEList->a[i].zName;
641 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000642 return i+1;
643 }
644 }
drh7d10d5a2008-08-20 16:35:10 +0000645 }
646 return 0;
647}
648
649/*
650** pE is a pointer to an expression which is a single term in the
651** ORDER BY of a compound SELECT. The expression has not been
652** name resolved.
653**
654** At the point this routine is called, we already know that the
655** ORDER BY term is not an integer index into the result set. That
656** case is handled by the calling routine.
657**
658** Attempt to match pE against result set columns in the left-most
659** SELECT statement. Return the index i of the matching column,
660** as an indication to the caller that it should sort by the i-th column.
661** The left-most column is 1. In other words, the value returned is the
662** same integer value that would be used in the SQL statement to indicate
663** the column.
664**
665** If there is no match, return 0. Return -1 if an error occurs.
666*/
667static int resolveOrderByTermToExprList(
668 Parse *pParse, /* Parsing context for error messages */
669 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
670 Expr *pE /* The specific ORDER BY term */
671){
672 int i; /* Loop counter */
673 ExprList *pEList; /* The columns of the result set */
674 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000675 sqlite3 *db; /* Database connection */
676 int rc; /* Return code from subprocedures */
677 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000678
679 assert( sqlite3ExprIsInteger(pE, &i)==0 );
680 pEList = pSelect->pEList;
681
682 /* Resolve all names in the ORDER BY term expression
683 */
684 memset(&nc, 0, sizeof(nc));
685 nc.pParse = pParse;
686 nc.pSrcList = pSelect->pSrc;
687 nc.pEList = pEList;
688 nc.allowAgg = 1;
689 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000690 db = pParse->db;
691 savedSuppErr = db->suppressErr;
692 db->suppressErr = 1;
693 rc = sqlite3ResolveExprNames(&nc, pE);
694 db->suppressErr = savedSuppErr;
695 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000696
697 /* Try to match the ORDER BY expression against an expression
698 ** in the result set. Return an 1-based index of the matching
699 ** result-set entry.
700 */
701 for(i=0; i<pEList->nExpr; i++){
drh1d9da702010-01-07 15:17:02 +0000702 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000703 return i+1;
704 }
705 }
706
707 /* If no match, return 0. */
708 return 0;
709}
710
711/*
712** Generate an ORDER BY or GROUP BY term out-of-range error.
713*/
714static void resolveOutOfRangeError(
715 Parse *pParse, /* The error context into which to write the error */
716 const char *zType, /* "ORDER" or "GROUP" */
717 int i, /* The index (1-based) of the term out of range */
718 int mx /* Largest permissible value of i */
719){
720 sqlite3ErrorMsg(pParse,
721 "%r %s BY term out of range - should be "
722 "between 1 and %d", i, zType, mx);
723}
724
725/*
726** Analyze the ORDER BY clause in a compound SELECT statement. Modify
727** each term of the ORDER BY clause is a constant integer between 1
728** and N where N is the number of columns in the compound SELECT.
729**
730** ORDER BY terms that are already an integer between 1 and N are
731** unmodified. ORDER BY terms that are integers outside the range of
732** 1 through N generate an error. ORDER BY terms that are expressions
733** are matched against result set expressions of compound SELECT
734** beginning with the left-most SELECT and working toward the right.
735** At the first match, the ORDER BY expression is transformed into
736** the integer column number.
737**
738** Return the number of errors seen.
739*/
740static int resolveCompoundOrderBy(
741 Parse *pParse, /* Parsing context. Leave error messages here */
742 Select *pSelect /* The SELECT statement containing the ORDER BY */
743){
744 int i;
745 ExprList *pOrderBy;
746 ExprList *pEList;
747 sqlite3 *db;
748 int moreToDo = 1;
749
750 pOrderBy = pSelect->pOrderBy;
751 if( pOrderBy==0 ) return 0;
752 db = pParse->db;
753#if SQLITE_MAX_COLUMN
754 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
755 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
756 return 1;
757 }
758#endif
759 for(i=0; i<pOrderBy->nExpr; i++){
760 pOrderBy->a[i].done = 0;
761 }
762 pSelect->pNext = 0;
763 while( pSelect->pPrior ){
764 pSelect->pPrior->pNext = pSelect;
765 pSelect = pSelect->pPrior;
766 }
767 while( pSelect && moreToDo ){
768 struct ExprList_item *pItem;
769 moreToDo = 0;
770 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000771 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000772 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
773 int iCol = -1;
774 Expr *pE, *pDup;
775 if( pItem->done ) continue;
776 pE = pItem->pExpr;
777 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000778 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000779 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
780 return 1;
781 }
782 }else{
783 iCol = resolveAsName(pParse, pEList, pE);
784 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000785 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000786 if( !db->mallocFailed ){
787 assert(pDup);
788 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
789 }
790 sqlite3ExprDelete(db, pDup);
791 }
drh7d10d5a2008-08-20 16:35:10 +0000792 }
793 if( iCol>0 ){
794 CollSeq *pColl = pE->pColl;
795 int flags = pE->flags & EP_ExpCollate;
796 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000797 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000798 if( pE==0 ) return 1;
799 pE->pColl = pColl;
800 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000801 pE->u.iValue = iCol;
drh4b3ac732011-12-10 23:18:32 +0000802 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000803 pItem->done = 1;
804 }else{
805 moreToDo = 1;
806 }
807 }
808 pSelect = pSelect->pNext;
809 }
810 for(i=0; i<pOrderBy->nExpr; i++){
811 if( pOrderBy->a[i].done==0 ){
812 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
813 "column in the result set", i+1);
814 return 1;
815 }
816 }
817 return 0;
818}
819
820/*
821** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
822** the SELECT statement pSelect. If any term is reference to a
823** result set expression (as determined by the ExprList.a.iCol field)
824** then convert that term into a copy of the corresponding result set
825** column.
826**
827** If any errors are detected, add an error message to pParse and
828** return non-zero. Return zero if no errors are seen.
829*/
830int sqlite3ResolveOrderGroupBy(
831 Parse *pParse, /* Parsing context. Leave error messages here */
832 Select *pSelect, /* The SELECT statement containing the clause */
833 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
834 const char *zType /* "ORDER" or "GROUP" */
835){
836 int i;
837 sqlite3 *db = pParse->db;
838 ExprList *pEList;
839 struct ExprList_item *pItem;
840
841 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
842#if SQLITE_MAX_COLUMN
843 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
844 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
845 return 1;
846 }
847#endif
848 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000849 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000850 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drh4b3ac732011-12-10 23:18:32 +0000851 if( pItem->iOrderByCol ){
852 if( pItem->iOrderByCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000853 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
854 return 1;
855 }
drh4b3ac732011-12-10 23:18:32 +0000856 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000857 }
858 }
859 return 0;
860}
861
862/*
863** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
864** The Name context of the SELECT statement is pNC. zType is either
865** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
866**
867** This routine resolves each term of the clause into an expression.
868** If the order-by term is an integer I between 1 and N (where N is the
869** number of columns in the result set of the SELECT) then the expression
870** in the resolution is a copy of the I-th result-set expression. If
871** the order-by term is an identify that corresponds to the AS-name of
872** a result-set expression, then the term resolves to a copy of the
873** result-set expression. Otherwise, the expression is resolved in
874** the usual way - using sqlite3ResolveExprNames().
875**
876** This routine returns the number of errors. If errors occur, then
877** an appropriate error message might be left in pParse. (OOM errors
878** excepted.)
879*/
880static int resolveOrderGroupBy(
881 NameContext *pNC, /* The name context of the SELECT statement */
882 Select *pSelect, /* The SELECT statement holding pOrderBy */
883 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
884 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
885){
drh70331cd2012-04-27 01:09:06 +0000886 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000887 int iCol; /* Column number */
888 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
889 Parse *pParse; /* Parsing context */
890 int nResult; /* Number of terms in the result set */
891
892 if( pOrderBy==0 ) return 0;
893 nResult = pSelect->pEList->nExpr;
894 pParse = pNC->pParse;
895 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
896 Expr *pE = pItem->pExpr;
897 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000898 if( iCol>0 ){
899 /* If an AS-name match is found, mark this ORDER BY column as being
900 ** a copy of the iCol-th result-set column. The subsequent call to
901 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
902 ** copy of the iCol-th result-set expression. */
drh4b3ac732011-12-10 23:18:32 +0000903 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000904 continue;
905 }
906 if( sqlite3ExprIsInteger(pE, &iCol) ){
907 /* The ORDER BY term is an integer constant. Again, set the column
908 ** number so that sqlite3ResolveOrderGroupBy() will convert the
909 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000910 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000911 resolveOutOfRangeError(pParse, zType, i+1, nResult);
912 return 1;
913 }
drh4b3ac732011-12-10 23:18:32 +0000914 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000915 continue;
916 }
917
918 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drh4b3ac732011-12-10 23:18:32 +0000919 pItem->iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:10 +0000920 if( sqlite3ResolveExprNames(pNC, pE) ){
921 return 1;
922 }
drh70331cd2012-04-27 01:09:06 +0000923 for(j=0; j<pSelect->pEList->nExpr; j++){
924 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
925 pItem->iOrderByCol = j+1;
926 }
927 }
drh7d10d5a2008-08-20 16:35:10 +0000928 }
929 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
930}
931
932/*
933** Resolve names in the SELECT statement p and all of its descendents.
934*/
935static int resolveSelectStep(Walker *pWalker, Select *p){
936 NameContext *pOuterNC; /* Context that contains this SELECT */
937 NameContext sNC; /* Name context of this SELECT */
938 int isCompound; /* True if p is a compound select */
939 int nCompound; /* Number of compound terms processed so far */
940 Parse *pParse; /* Parsing context */
941 ExprList *pEList; /* Result set expression list */
942 int i; /* Loop counter */
943 ExprList *pGroupBy; /* The GROUP BY clause */
944 Select *pLeftmost; /* Left-most of SELECT of a compound */
945 sqlite3 *db; /* Database connection */
946
947
drh0a846f92008-08-25 17:23:29 +0000948 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000949 if( p->selFlags & SF_Resolved ){
950 return WRC_Prune;
951 }
952 pOuterNC = pWalker->u.pNC;
953 pParse = pWalker->pParse;
954 db = pParse->db;
955
956 /* Normally sqlite3SelectExpand() will be called first and will have
957 ** already expanded this SELECT. However, if this is a subquery within
958 ** an expression, sqlite3ResolveExprNames() will be called without a
959 ** prior call to sqlite3SelectExpand(). When that happens, let
960 ** sqlite3SelectPrep() do all of the processing for this SELECT.
961 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
962 ** this routine in the correct order.
963 */
964 if( (p->selFlags & SF_Expanded)==0 ){
965 sqlite3SelectPrep(pParse, p, pOuterNC);
966 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
967 }
968
969 isCompound = p->pPrior!=0;
970 nCompound = 0;
971 pLeftmost = p;
972 while( p ){
973 assert( (p->selFlags & SF_Expanded)!=0 );
974 assert( (p->selFlags & SF_Resolved)==0 );
975 p->selFlags |= SF_Resolved;
976
977 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
978 ** are not allowed to refer to any names, so pass an empty NameContext.
979 */
980 memset(&sNC, 0, sizeof(sNC));
981 sNC.pParse = pParse;
982 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
983 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
984 return WRC_Abort;
985 }
986
987 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
988 ** resolve the result-set expression list.
989 */
990 sNC.allowAgg = 1;
991 sNC.pSrcList = p->pSrc;
992 sNC.pNext = pOuterNC;
993
994 /* Resolve names in the result set. */
995 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000996 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000997 for(i=0; i<pEList->nExpr; i++){
998 Expr *pX = pEList->a[i].pExpr;
999 if( sqlite3ResolveExprNames(&sNC, pX) ){
1000 return WRC_Abort;
1001 }
1002 }
1003
1004 /* Recursively resolve names in all subqueries
1005 */
1006 for(i=0; i<p->pSrc->nSrc; i++){
1007 struct SrcList_item *pItem = &p->pSrc->a[i];
1008 if( pItem->pSelect ){
danda79cf02011-07-08 16:10:54 +00001009 NameContext *pNC; /* Used to iterate name contexts */
1010 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
drh7d10d5a2008-08-20 16:35:10 +00001011 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:54 +00001012
1013 /* Count the total number of references to pOuterNC and all of its
1014 ** parent contexts. After resolving references to expressions in
1015 ** pItem->pSelect, check if this value has changed. If so, then
1016 ** SELECT statement pItem->pSelect must be correlated. Set the
1017 ** pItem->isCorrelated flag if this is the case. */
1018 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1019
drh7d10d5a2008-08-20 16:35:10 +00001020 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +00001021 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +00001022 pParse->zAuthContext = zSavedContext;
1023 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
danda79cf02011-07-08 16:10:54 +00001024
1025 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1026 assert( pItem->isCorrelated==0 && nRef<=0 );
1027 pItem->isCorrelated = (nRef!=0);
drh7d10d5a2008-08-20 16:35:10 +00001028 }
1029 }
1030
1031 /* If there are no aggregate functions in the result-set, and no GROUP BY
1032 ** expression, do not allow aggregates in any of the other expressions.
1033 */
1034 assert( (p->selFlags & SF_Aggregate)==0 );
1035 pGroupBy = p->pGroupBy;
1036 if( pGroupBy || sNC.hasAgg ){
1037 p->selFlags |= SF_Aggregate;
1038 }else{
1039 sNC.allowAgg = 0;
1040 }
1041
1042 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1043 */
1044 if( p->pHaving && !pGroupBy ){
1045 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1046 return WRC_Abort;
1047 }
1048
1049 /* Add the expression list to the name-context before parsing the
1050 ** other expressions in the SELECT statement. This is so that
1051 ** expressions in the WHERE clause (etc.) can refer to expressions by
1052 ** aliases in the result set.
1053 **
1054 ** Minor point: If this is the case, then the expression will be
1055 ** re-evaluated for each reference to it.
1056 */
1057 sNC.pEList = p->pEList;
1058 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1059 sqlite3ResolveExprNames(&sNC, p->pHaving)
1060 ){
1061 return WRC_Abort;
1062 }
1063
1064 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1065 ** outer queries
1066 */
1067 sNC.pNext = 0;
1068 sNC.allowAgg = 1;
1069
1070 /* Process the ORDER BY clause for singleton SELECT statements.
1071 ** The ORDER BY clause for compounds SELECT statements is handled
1072 ** below, after all of the result-sets for all of the elements of
1073 ** the compound have been resolved.
1074 */
1075 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1076 return WRC_Abort;
1077 }
1078 if( db->mallocFailed ){
1079 return WRC_Abort;
1080 }
1081
1082 /* Resolve the GROUP BY clause. At the same time, make sure
1083 ** the GROUP BY clause does not contain aggregate functions.
1084 */
1085 if( pGroupBy ){
1086 struct ExprList_item *pItem;
1087
1088 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1089 return WRC_Abort;
1090 }
1091 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1092 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1093 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1094 "the GROUP BY clause");
1095 return WRC_Abort;
1096 }
1097 }
1098 }
1099
1100 /* Advance to the next term of the compound
1101 */
1102 p = p->pPrior;
1103 nCompound++;
1104 }
1105
1106 /* Resolve the ORDER BY on a compound SELECT after all terms of
1107 ** the compound have been resolved.
1108 */
1109 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1110 return WRC_Abort;
1111 }
1112
1113 return WRC_Prune;
1114}
1115
1116/*
1117** This routine walks an expression tree and resolves references to
1118** table columns and result-set columns. At the same time, do error
1119** checking on function usage and set a flag if any aggregate functions
1120** are seen.
1121**
1122** To resolve table columns references we look for nodes (or subtrees) of the
1123** form X.Y.Z or Y.Z or just Z where
1124**
1125** X: The name of a database. Ex: "main" or "temp" or
1126** the symbolic name assigned to an ATTACH-ed database.
1127**
1128** Y: The name of a table in a FROM clause. Or in a trigger
1129** one of the special names "old" or "new".
1130**
1131** Z: The name of a column in table Y.
1132**
1133** The node at the root of the subtree is modified as follows:
1134**
1135** Expr.op Changed to TK_COLUMN
1136** Expr.pTab Points to the Table object for X.Y
1137** Expr.iColumn The column index in X.Y. -1 for the rowid.
1138** Expr.iTable The VDBE cursor number for X.Y
1139**
1140**
1141** To resolve result-set references, look for expression nodes of the
1142** form Z (with no X and Y prefix) where the Z matches the right-hand
1143** size of an AS clause in the result-set of a SELECT. The Z expression
1144** is replaced by a copy of the left-hand side of the result-set expression.
1145** Table-name and function resolution occurs on the substituted expression
1146** tree. For example, in:
1147**
1148** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1149**
1150** The "x" term of the order by is replaced by "a+b" to render:
1151**
1152** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1153**
1154** Function calls are checked to make sure that the function is
1155** defined and that the correct number of arguments are specified.
1156** If the function is an aggregate function, then the pNC->hasAgg is
1157** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1158** If an expression contains aggregate functions then the EP_Agg
1159** property on the expression is set.
1160**
1161** An error message is left in pParse if anything is amiss. The number
1162** if errors is returned.
1163*/
1164int sqlite3ResolveExprNames(
1165 NameContext *pNC, /* Namespace to resolve expressions in. */
1166 Expr *pExpr /* The expression to be analyzed. */
1167){
1168 int savedHasAgg;
1169 Walker w;
1170
1171 if( pExpr==0 ) return 0;
1172#if SQLITE_MAX_EXPR_DEPTH>0
1173 {
1174 Parse *pParse = pNC->pParse;
1175 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1176 return 1;
1177 }
1178 pParse->nHeight += pExpr->nHeight;
1179 }
1180#endif
1181 savedHasAgg = pNC->hasAgg;
1182 pNC->hasAgg = 0;
1183 w.xExprCallback = resolveExprStep;
1184 w.xSelectCallback = resolveSelectStep;
1185 w.pParse = pNC->pParse;
1186 w.u.pNC = pNC;
1187 sqlite3WalkExpr(&w, pExpr);
1188#if SQLITE_MAX_EXPR_DEPTH>0
1189 pNC->pParse->nHeight -= pExpr->nHeight;
1190#endif
drhfd773cf2009-05-29 14:39:07 +00001191 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001192 ExprSetProperty(pExpr, EP_Error);
1193 }
1194 if( pNC->hasAgg ){
1195 ExprSetProperty(pExpr, EP_Agg);
1196 }else if( savedHasAgg ){
1197 pNC->hasAgg = 1;
1198 }
1199 return ExprHasProperty(pExpr, EP_Error);
1200}
drh7d10d5a2008-08-20 16:35:10 +00001201
1202
1203/*
1204** Resolve all names in all expressions of a SELECT and in all
1205** decendents of the SELECT, including compounds off of p->pPrior,
1206** subqueries in expressions, and subqueries used as FROM clause
1207** terms.
1208**
1209** See sqlite3ResolveExprNames() for a description of the kinds of
1210** transformations that occur.
1211**
1212** All SELECT statements should have been expanded using
1213** sqlite3SelectExpand() prior to invoking this routine.
1214*/
1215void sqlite3ResolveSelectNames(
1216 Parse *pParse, /* The parser context */
1217 Select *p, /* The SELECT statement being coded. */
1218 NameContext *pOuterNC /* Name context for parent SELECT statement */
1219){
1220 Walker w;
1221
drh0a846f92008-08-25 17:23:29 +00001222 assert( p!=0 );
1223 w.xExprCallback = resolveExprStep;
1224 w.xSelectCallback = resolveSelectStep;
1225 w.pParse = pParse;
1226 w.u.pNC = pOuterNC;
1227 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001228}