blob: bfbcd20419b8f27c951aa0aa001be5c8fea32c3c [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;
drha51009b2012-05-21 19:11:25 +0000314 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
drh7d10d5a2008-08-20 16:35:10 +0000315 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
drha51009b2012-05-21 19:11:25 +0000559 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000560 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 }
drha51009b2012-05-21 19:11:25 +0000571 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000572 sqlite3WalkExprList(pWalker, pList);
drh030796d2012-08-23 16:18:10 +0000573 if( is_agg ){
574 NameContext *pNC2 = pNC;
575 pExpr->op = TK_AGG_FUNCTION;
576 pExpr->op2 = 0;
577 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
578 pExpr->op2++;
579 pNC2 = pNC2->pNext;
580 }
581 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
582 pNC->ncFlags |= NC_AllowAgg;
583 }
drh7d10d5a2008-08-20 16:35:10 +0000584 /* FIX ME: Compute pExpr->affinity based on the expected return
585 ** type of the function
586 */
587 return WRC_Prune;
588 }
589#ifndef SQLITE_OMIT_SUBQUERY
590 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000591 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000592#endif
593 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000594 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000595 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000596 int nRef = pNC->nRef;
597#ifndef SQLITE_OMIT_CHECK
drha51009b2012-05-21 19:11:25 +0000598 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000599 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
600 }
601#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000602 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000603 assert( pNC->nRef>=nRef );
604 if( nRef!=pNC->nRef ){
605 ExprSetProperty(pExpr, EP_VarSelect);
606 }
607 }
608 break;
609 }
610#ifndef SQLITE_OMIT_CHECK
611 case TK_VARIABLE: {
drha51009b2012-05-21 19:11:25 +0000612 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000613 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
614 }
615 break;
616 }
617#endif
618 }
619 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
620}
621
622/*
623** pEList is a list of expressions which are really the result set of the
624** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
625** This routine checks to see if pE is a simple identifier which corresponds
626** to the AS-name of one of the terms of the expression list. If it is,
627** this routine return an integer between 1 and N where N is the number of
628** elements in pEList, corresponding to the matching entry. If there is
629** no match, or if pE is not a simple identifier, then this routine
630** return 0.
631**
632** pEList has been resolved. pE has not.
633*/
634static int resolveAsName(
635 Parse *pParse, /* Parsing context for error messages */
636 ExprList *pEList, /* List of expressions to scan */
637 Expr *pE /* Expression we are trying to match */
638){
639 int i; /* Loop counter */
640
shanecf697392009-06-01 16:53:09 +0000641 UNUSED_PARAMETER(pParse);
642
drh73c0fdc2009-06-15 18:32:36 +0000643 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000644 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000645 for(i=0; i<pEList->nExpr; i++){
646 char *zAs = pEList->a[i].zName;
647 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000648 return i+1;
649 }
650 }
drh7d10d5a2008-08-20 16:35:10 +0000651 }
652 return 0;
653}
654
655/*
656** pE is a pointer to an expression which is a single term in the
657** ORDER BY of a compound SELECT. The expression has not been
658** name resolved.
659**
660** At the point this routine is called, we already know that the
661** ORDER BY term is not an integer index into the result set. That
662** case is handled by the calling routine.
663**
664** Attempt to match pE against result set columns in the left-most
665** SELECT statement. Return the index i of the matching column,
666** as an indication to the caller that it should sort by the i-th column.
667** The left-most column is 1. In other words, the value returned is the
668** same integer value that would be used in the SQL statement to indicate
669** the column.
670**
671** If there is no match, return 0. Return -1 if an error occurs.
672*/
673static int resolveOrderByTermToExprList(
674 Parse *pParse, /* Parsing context for error messages */
675 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
676 Expr *pE /* The specific ORDER BY term */
677){
678 int i; /* Loop counter */
679 ExprList *pEList; /* The columns of the result set */
680 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000681 sqlite3 *db; /* Database connection */
682 int rc; /* Return code from subprocedures */
683 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000684
685 assert( sqlite3ExprIsInteger(pE, &i)==0 );
686 pEList = pSelect->pEList;
687
688 /* Resolve all names in the ORDER BY term expression
689 */
690 memset(&nc, 0, sizeof(nc));
691 nc.pParse = pParse;
692 nc.pSrcList = pSelect->pSrc;
693 nc.pEList = pEList;
drha51009b2012-05-21 19:11:25 +0000694 nc.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000695 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000696 db = pParse->db;
697 savedSuppErr = db->suppressErr;
698 db->suppressErr = 1;
699 rc = sqlite3ResolveExprNames(&nc, pE);
700 db->suppressErr = savedSuppErr;
701 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000702
703 /* Try to match the ORDER BY expression against an expression
704 ** in the result set. Return an 1-based index of the matching
705 ** result-set entry.
706 */
707 for(i=0; i<pEList->nExpr; i++){
drh1d9da702010-01-07 15:17:02 +0000708 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000709 return i+1;
710 }
711 }
712
713 /* If no match, return 0. */
714 return 0;
715}
716
717/*
718** Generate an ORDER BY or GROUP BY term out-of-range error.
719*/
720static void resolveOutOfRangeError(
721 Parse *pParse, /* The error context into which to write the error */
722 const char *zType, /* "ORDER" or "GROUP" */
723 int i, /* The index (1-based) of the term out of range */
724 int mx /* Largest permissible value of i */
725){
726 sqlite3ErrorMsg(pParse,
727 "%r %s BY term out of range - should be "
728 "between 1 and %d", i, zType, mx);
729}
730
731/*
732** Analyze the ORDER BY clause in a compound SELECT statement. Modify
733** each term of the ORDER BY clause is a constant integer between 1
734** and N where N is the number of columns in the compound SELECT.
735**
736** ORDER BY terms that are already an integer between 1 and N are
737** unmodified. ORDER BY terms that are integers outside the range of
738** 1 through N generate an error. ORDER BY terms that are expressions
739** are matched against result set expressions of compound SELECT
740** beginning with the left-most SELECT and working toward the right.
741** At the first match, the ORDER BY expression is transformed into
742** the integer column number.
743**
744** Return the number of errors seen.
745*/
746static int resolveCompoundOrderBy(
747 Parse *pParse, /* Parsing context. Leave error messages here */
748 Select *pSelect /* The SELECT statement containing the ORDER BY */
749){
750 int i;
751 ExprList *pOrderBy;
752 ExprList *pEList;
753 sqlite3 *db;
754 int moreToDo = 1;
755
756 pOrderBy = pSelect->pOrderBy;
757 if( pOrderBy==0 ) return 0;
758 db = pParse->db;
759#if SQLITE_MAX_COLUMN
760 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
761 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
762 return 1;
763 }
764#endif
765 for(i=0; i<pOrderBy->nExpr; i++){
766 pOrderBy->a[i].done = 0;
767 }
768 pSelect->pNext = 0;
769 while( pSelect->pPrior ){
770 pSelect->pPrior->pNext = pSelect;
771 pSelect = pSelect->pPrior;
772 }
773 while( pSelect && moreToDo ){
774 struct ExprList_item *pItem;
775 moreToDo = 0;
776 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000777 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000778 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
779 int iCol = -1;
780 Expr *pE, *pDup;
781 if( pItem->done ) continue;
782 pE = pItem->pExpr;
783 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000784 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000785 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
786 return 1;
787 }
788 }else{
789 iCol = resolveAsName(pParse, pEList, pE);
790 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000791 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000792 if( !db->mallocFailed ){
793 assert(pDup);
794 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
795 }
796 sqlite3ExprDelete(db, pDup);
797 }
drh7d10d5a2008-08-20 16:35:10 +0000798 }
799 if( iCol>0 ){
800 CollSeq *pColl = pE->pColl;
801 int flags = pE->flags & EP_ExpCollate;
802 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000803 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000804 if( pE==0 ) return 1;
805 pE->pColl = pColl;
806 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000807 pE->u.iValue = iCol;
drh4b3ac732011-12-10 23:18:32 +0000808 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000809 pItem->done = 1;
810 }else{
811 moreToDo = 1;
812 }
813 }
814 pSelect = pSelect->pNext;
815 }
816 for(i=0; i<pOrderBy->nExpr; i++){
817 if( pOrderBy->a[i].done==0 ){
818 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
819 "column in the result set", i+1);
820 return 1;
821 }
822 }
823 return 0;
824}
825
826/*
827** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
828** the SELECT statement pSelect. If any term is reference to a
829** result set expression (as determined by the ExprList.a.iCol field)
830** then convert that term into a copy of the corresponding result set
831** column.
832**
833** If any errors are detected, add an error message to pParse and
834** return non-zero. Return zero if no errors are seen.
835*/
836int sqlite3ResolveOrderGroupBy(
837 Parse *pParse, /* Parsing context. Leave error messages here */
838 Select *pSelect, /* The SELECT statement containing the clause */
839 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
840 const char *zType /* "ORDER" or "GROUP" */
841){
842 int i;
843 sqlite3 *db = pParse->db;
844 ExprList *pEList;
845 struct ExprList_item *pItem;
846
847 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
848#if SQLITE_MAX_COLUMN
849 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
850 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
851 return 1;
852 }
853#endif
854 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000855 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000856 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drh4b3ac732011-12-10 23:18:32 +0000857 if( pItem->iOrderByCol ){
858 if( pItem->iOrderByCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000859 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
860 return 1;
861 }
drh4b3ac732011-12-10 23:18:32 +0000862 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000863 }
864 }
865 return 0;
866}
867
868/*
869** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
870** The Name context of the SELECT statement is pNC. zType is either
871** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
872**
873** This routine resolves each term of the clause into an expression.
874** If the order-by term is an integer I between 1 and N (where N is the
875** number of columns in the result set of the SELECT) then the expression
876** in the resolution is a copy of the I-th result-set expression. If
877** the order-by term is an identify that corresponds to the AS-name of
878** a result-set expression, then the term resolves to a copy of the
879** result-set expression. Otherwise, the expression is resolved in
880** the usual way - using sqlite3ResolveExprNames().
881**
882** This routine returns the number of errors. If errors occur, then
883** an appropriate error message might be left in pParse. (OOM errors
884** excepted.)
885*/
886static int resolveOrderGroupBy(
887 NameContext *pNC, /* The name context of the SELECT statement */
888 Select *pSelect, /* The SELECT statement holding pOrderBy */
889 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
890 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
891){
drh70331cd2012-04-27 01:09:06 +0000892 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000893 int iCol; /* Column number */
894 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
895 Parse *pParse; /* Parsing context */
896 int nResult; /* Number of terms in the result set */
897
898 if( pOrderBy==0 ) return 0;
899 nResult = pSelect->pEList->nExpr;
900 pParse = pNC->pParse;
901 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
902 Expr *pE = pItem->pExpr;
903 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000904 if( iCol>0 ){
905 /* If an AS-name match is found, mark this ORDER BY column as being
906 ** a copy of the iCol-th result-set column. The subsequent call to
907 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
908 ** copy of the iCol-th result-set expression. */
drh4b3ac732011-12-10 23:18:32 +0000909 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000910 continue;
911 }
912 if( sqlite3ExprIsInteger(pE, &iCol) ){
913 /* The ORDER BY term is an integer constant. Again, set the column
914 ** number so that sqlite3ResolveOrderGroupBy() will convert the
915 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000916 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000917 resolveOutOfRangeError(pParse, zType, i+1, nResult);
918 return 1;
919 }
drh4b3ac732011-12-10 23:18:32 +0000920 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000921 continue;
922 }
923
924 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drh4b3ac732011-12-10 23:18:32 +0000925 pItem->iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:10 +0000926 if( sqlite3ResolveExprNames(pNC, pE) ){
927 return 1;
928 }
drh70331cd2012-04-27 01:09:06 +0000929 for(j=0; j<pSelect->pEList->nExpr; j++){
930 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
931 pItem->iOrderByCol = j+1;
932 }
933 }
drh7d10d5a2008-08-20 16:35:10 +0000934 }
935 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
936}
937
938/*
939** Resolve names in the SELECT statement p and all of its descendents.
940*/
941static int resolveSelectStep(Walker *pWalker, Select *p){
942 NameContext *pOuterNC; /* Context that contains this SELECT */
943 NameContext sNC; /* Name context of this SELECT */
944 int isCompound; /* True if p is a compound select */
945 int nCompound; /* Number of compound terms processed so far */
946 Parse *pParse; /* Parsing context */
947 ExprList *pEList; /* Result set expression list */
948 int i; /* Loop counter */
949 ExprList *pGroupBy; /* The GROUP BY clause */
950 Select *pLeftmost; /* Left-most of SELECT of a compound */
951 sqlite3 *db; /* Database connection */
952
953
drh0a846f92008-08-25 17:23:29 +0000954 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000955 if( p->selFlags & SF_Resolved ){
956 return WRC_Prune;
957 }
958 pOuterNC = pWalker->u.pNC;
959 pParse = pWalker->pParse;
960 db = pParse->db;
961
962 /* Normally sqlite3SelectExpand() will be called first and will have
963 ** already expanded this SELECT. However, if this is a subquery within
964 ** an expression, sqlite3ResolveExprNames() will be called without a
965 ** prior call to sqlite3SelectExpand(). When that happens, let
966 ** sqlite3SelectPrep() do all of the processing for this SELECT.
967 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
968 ** this routine in the correct order.
969 */
970 if( (p->selFlags & SF_Expanded)==0 ){
971 sqlite3SelectPrep(pParse, p, pOuterNC);
972 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
973 }
974
975 isCompound = p->pPrior!=0;
976 nCompound = 0;
977 pLeftmost = p;
978 while( p ){
979 assert( (p->selFlags & SF_Expanded)!=0 );
980 assert( (p->selFlags & SF_Resolved)==0 );
981 p->selFlags |= SF_Resolved;
982
983 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
984 ** are not allowed to refer to any names, so pass an empty NameContext.
985 */
986 memset(&sNC, 0, sizeof(sNC));
987 sNC.pParse = pParse;
988 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
989 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
990 return WRC_Abort;
991 }
992
993 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
994 ** resolve the result-set expression list.
995 */
drha51009b2012-05-21 19:11:25 +0000996 sNC.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000997 sNC.pSrcList = p->pSrc;
998 sNC.pNext = pOuterNC;
999
1000 /* Resolve names in the result set. */
1001 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +00001002 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00001003 for(i=0; i<pEList->nExpr; i++){
1004 Expr *pX = pEList->a[i].pExpr;
1005 if( sqlite3ResolveExprNames(&sNC, pX) ){
1006 return WRC_Abort;
1007 }
1008 }
1009
1010 /* Recursively resolve names in all subqueries
1011 */
1012 for(i=0; i<p->pSrc->nSrc; i++){
1013 struct SrcList_item *pItem = &p->pSrc->a[i];
1014 if( pItem->pSelect ){
danda79cf02011-07-08 16:10:54 +00001015 NameContext *pNC; /* Used to iterate name contexts */
1016 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
drh7d10d5a2008-08-20 16:35:10 +00001017 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:54 +00001018
1019 /* Count the total number of references to pOuterNC and all of its
1020 ** parent contexts. After resolving references to expressions in
1021 ** pItem->pSelect, check if this value has changed. If so, then
1022 ** SELECT statement pItem->pSelect must be correlated. Set the
1023 ** pItem->isCorrelated flag if this is the case. */
1024 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1025
drh7d10d5a2008-08-20 16:35:10 +00001026 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +00001027 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +00001028 pParse->zAuthContext = zSavedContext;
1029 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
danda79cf02011-07-08 16:10:54 +00001030
1031 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1032 assert( pItem->isCorrelated==0 && nRef<=0 );
1033 pItem->isCorrelated = (nRef!=0);
drh7d10d5a2008-08-20 16:35:10 +00001034 }
1035 }
1036
1037 /* If there are no aggregate functions in the result-set, and no GROUP BY
1038 ** expression, do not allow aggregates in any of the other expressions.
1039 */
1040 assert( (p->selFlags & SF_Aggregate)==0 );
1041 pGroupBy = p->pGroupBy;
drha51009b2012-05-21 19:11:25 +00001042 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +00001043 p->selFlags |= SF_Aggregate;
1044 }else{
drha51009b2012-05-21 19:11:25 +00001045 sNC.ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001046 }
1047
1048 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1049 */
1050 if( p->pHaving && !pGroupBy ){
1051 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1052 return WRC_Abort;
1053 }
1054
1055 /* Add the expression list to the name-context before parsing the
1056 ** other expressions in the SELECT statement. This is so that
1057 ** expressions in the WHERE clause (etc.) can refer to expressions by
1058 ** aliases in the result set.
1059 **
1060 ** Minor point: If this is the case, then the expression will be
1061 ** re-evaluated for each reference to it.
1062 */
1063 sNC.pEList = p->pEList;
1064 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1065 sqlite3ResolveExprNames(&sNC, p->pHaving)
1066 ){
1067 return WRC_Abort;
1068 }
1069
1070 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1071 ** outer queries
1072 */
1073 sNC.pNext = 0;
drha51009b2012-05-21 19:11:25 +00001074 sNC.ncFlags |= NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001075
1076 /* Process the ORDER BY clause for singleton SELECT statements.
1077 ** The ORDER BY clause for compounds SELECT statements is handled
1078 ** below, after all of the result-sets for all of the elements of
1079 ** the compound have been resolved.
1080 */
1081 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1082 return WRC_Abort;
1083 }
1084 if( db->mallocFailed ){
1085 return WRC_Abort;
1086 }
1087
1088 /* Resolve the GROUP BY clause. At the same time, make sure
1089 ** the GROUP BY clause does not contain aggregate functions.
1090 */
1091 if( pGroupBy ){
1092 struct ExprList_item *pItem;
1093
1094 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1095 return WRC_Abort;
1096 }
1097 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1098 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1099 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1100 "the GROUP BY clause");
1101 return WRC_Abort;
1102 }
1103 }
1104 }
1105
1106 /* Advance to the next term of the compound
1107 */
1108 p = p->pPrior;
1109 nCompound++;
1110 }
1111
1112 /* Resolve the ORDER BY on a compound SELECT after all terms of
1113 ** the compound have been resolved.
1114 */
1115 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1116 return WRC_Abort;
1117 }
1118
1119 return WRC_Prune;
1120}
1121
1122/*
1123** This routine walks an expression tree and resolves references to
1124** table columns and result-set columns. At the same time, do error
1125** checking on function usage and set a flag if any aggregate functions
1126** are seen.
1127**
1128** To resolve table columns references we look for nodes (or subtrees) of the
1129** form X.Y.Z or Y.Z or just Z where
1130**
1131** X: The name of a database. Ex: "main" or "temp" or
1132** the symbolic name assigned to an ATTACH-ed database.
1133**
1134** Y: The name of a table in a FROM clause. Or in a trigger
1135** one of the special names "old" or "new".
1136**
1137** Z: The name of a column in table Y.
1138**
1139** The node at the root of the subtree is modified as follows:
1140**
1141** Expr.op Changed to TK_COLUMN
1142** Expr.pTab Points to the Table object for X.Y
1143** Expr.iColumn The column index in X.Y. -1 for the rowid.
1144** Expr.iTable The VDBE cursor number for X.Y
1145**
1146**
1147** To resolve result-set references, look for expression nodes of the
1148** form Z (with no X and Y prefix) where the Z matches the right-hand
1149** size of an AS clause in the result-set of a SELECT. The Z expression
1150** is replaced by a copy of the left-hand side of the result-set expression.
1151** Table-name and function resolution occurs on the substituted expression
1152** tree. For example, in:
1153**
1154** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1155**
1156** The "x" term of the order by is replaced by "a+b" to render:
1157**
1158** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1159**
1160** Function calls are checked to make sure that the function is
1161** defined and that the correct number of arguments are specified.
drha51009b2012-05-21 19:11:25 +00001162** If the function is an aggregate function, then the NC_HasAgg flag is
drh7d10d5a2008-08-20 16:35:10 +00001163** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1164** If an expression contains aggregate functions then the EP_Agg
1165** property on the expression is set.
1166**
1167** An error message is left in pParse if anything is amiss. The number
1168** if errors is returned.
1169*/
1170int sqlite3ResolveExprNames(
1171 NameContext *pNC, /* Namespace to resolve expressions in. */
1172 Expr *pExpr /* The expression to be analyzed. */
1173){
drha51009b2012-05-21 19:11:25 +00001174 u8 savedHasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001175 Walker w;
1176
1177 if( pExpr==0 ) return 0;
1178#if SQLITE_MAX_EXPR_DEPTH>0
1179 {
1180 Parse *pParse = pNC->pParse;
1181 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1182 return 1;
1183 }
1184 pParse->nHeight += pExpr->nHeight;
1185 }
1186#endif
drha51009b2012-05-21 19:11:25 +00001187 savedHasAgg = pNC->ncFlags & NC_HasAgg;
1188 pNC->ncFlags &= ~NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001189 w.xExprCallback = resolveExprStep;
1190 w.xSelectCallback = resolveSelectStep;
1191 w.pParse = pNC->pParse;
1192 w.u.pNC = pNC;
1193 sqlite3WalkExpr(&w, pExpr);
1194#if SQLITE_MAX_EXPR_DEPTH>0
1195 pNC->pParse->nHeight -= pExpr->nHeight;
1196#endif
drhfd773cf2009-05-29 14:39:07 +00001197 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001198 ExprSetProperty(pExpr, EP_Error);
1199 }
drha51009b2012-05-21 19:11:25 +00001200 if( pNC->ncFlags & NC_HasAgg ){
drh7d10d5a2008-08-20 16:35:10 +00001201 ExprSetProperty(pExpr, EP_Agg);
1202 }else if( savedHasAgg ){
drha51009b2012-05-21 19:11:25 +00001203 pNC->ncFlags |= NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001204 }
1205 return ExprHasProperty(pExpr, EP_Error);
1206}
drh7d10d5a2008-08-20 16:35:10 +00001207
1208
1209/*
1210** Resolve all names in all expressions of a SELECT and in all
1211** decendents of the SELECT, including compounds off of p->pPrior,
1212** subqueries in expressions, and subqueries used as FROM clause
1213** terms.
1214**
1215** See sqlite3ResolveExprNames() for a description of the kinds of
1216** transformations that occur.
1217**
1218** All SELECT statements should have been expanded using
1219** sqlite3SelectExpand() prior to invoking this routine.
1220*/
1221void sqlite3ResolveSelectNames(
1222 Parse *pParse, /* The parser context */
1223 Select *p, /* The SELECT statement being coded. */
1224 NameContext *pOuterNC /* Name context for parent SELECT statement */
1225){
1226 Walker w;
1227
drh0a846f92008-08-25 17:23:29 +00001228 assert( p!=0 );
1229 w.xExprCallback = resolveExprStep;
1230 w.xSelectCallback = resolveSelectStep;
1231 w.pParse = pParse;
1232 w.u.pNC = pOuterNC;
1233 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001234}